繁体   English   中英

C++中int类型到double类型以及不同类型的算术运算结果如何正确存储?

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

我有两次存储在struct中的int类型中,想要计算编号。 两次之间经过的小时数。 如何正确地将结果存储在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.25 时,我会得到错误的结果 7:

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

错误是因为此表达式(t2.min+t1.min)/60将返回int

那是因为(t2.min+t1.min)int类型,而60int类型。 因此\将是一个 integer 除法运算。

要解决它,您可以使用static_cast<double>(t2.min+t1.min)(t2.min+t1.min)转换为double 查看有关static_cast的更多信息。

或者您可以通过编写60.0简单地将60定义为双精度数。

由于您正在执行 integer 操作 '(t2.min + t1.min)/60',即使您将它们存储在 double 类型的变量中,也会简化为 integer 类型。 通过将 60 更改为“60.0”使 60 成为双精度值,或者在操作之前使用“static_cast”包含整个结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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