How to correctly store the result of arithmetic operations on int type to double type and different types in C++?

  c++, type-conversion, types

I have two times stored in int type in a struct and want to calculate the no. of hours elapsed in between two times. How do I correctly store the result of in a double variable. I seem to get the difference wrong. Also how do I store the result up to two places after the decimal point.
This is my code :

struct time
{
int hour=0,min=0;
char am_pm='a';
};

int main()
{
time t1,t2; 
// GET THE TIME INPUT FROM THE USER HERE
//assuming always t2's hour and min are always numerically greater than t1's hour and min and always `am`

double hour_diff=0.00,min_diff=0.00;
double time_elapsed=0.00;
cout<<"The time elapsed between your entered times is : ";

hour_diff=t2.hour-t1.hour; counting hour difference
min_diff=(t2.min+t1.min)/60; //counting total minutes and converting them into hours

time_elapsed=hour_diff+min_diff;
cout<<time_elapsed;

if i give these input i get wrong result 7 when i should get 7.25 :

INPUT
t1.hour = 5
t1.min = 30
t1.am_pm = a;

t2.hour = 11
t2.min = 45
t2.am_pm = a;

time elapsed = 7 // this is wrong, I should be getting 7.25

Source: Windows Questions C++

LEAVE A COMMENT