简体   繁体   中英

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

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

The error is because this expression (t2.min+t1.min)/60 will return int .

That's because (t2.min+t1.min) is of type int and 60 is of type int . Hence \ will be an integer division operation.

To resolve it you can convert your (t2.min+t1.min) to the double with static_cast<double>(t2.min+t1.min) . See more about static_cast .

Or you can simply define 60 as a double by writing 60.0 .

Since you are performing integer operations '(t2.min + t1.min)/60', even though you are storing them in a variable of type double, become simplified to an integer type. Either make 60 a double by changing it to '60.0' or encompass the whole result with a 'static_cast' before your operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM