【发布时间】:2021-03-15 03:24:37
【问题描述】:
我在int 中存储了两次struct 并想计算编号。两次之间经过的小时数。如何正确地将结果存储在 double 变量中。我似乎弄错了区别。另外,如何将结果存储到小数点后两位。
这是我的代码:
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;
如果我给出这些输入,我会得到错误的结果 7,而我应该得到 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
【问题讨论】:
-
试试
min_diff=(t2.min+t1.min)/60.0;。 -
@songyuanyao 是对的。
(t2.min+t1.min)/60的所有子表达式(变量和文字)都是整数,所以表达式也是整数。就像int i = 5/3;中的 i 是 1(即,(double(i) == 1.0成立)一样,表达式的值只是整数分数。如果您将其中一个操作数更改为浮点数或双精度数,使用它进行操作的操作数(此处:(t2.min+t1.min)也将转换为浮点数或双精度数,生成的表达式将为浮点数或双精度数。
标签: c++ types type-conversion