【问题标题】:How to correctly store the result of arithmetic operations on int type to double type and different types in C++?如何正确地将 int 类型的算术运算结果存储为 C++ 中的 double 类型和不同类型?
【发布时间】: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


【解决方案1】:

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

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

要解决此问题,您可以使用 static_cast&lt;double&gt;(t2.min+t1.min) 将您的 (t2.min+t1.min) 转换为 double。查看更多关于static_cast的信息。

或者您可以通过编写60.060 简单地定义为double。

【讨论】:

  • 你能解释一下如何只得到小数点后两位吗?
  • 能否也解释一下如何只得到小数点后两位?\
  • @PratapBiswakarma 如果您只需要打印输出 2 个小数点,那么您可以使用:stackoverflow.com/questions/5907031/… 如果您只想存储 2 个小数点。然后你可以将你的数字乘以 100、floorceilround 然后除以 100。
【解决方案2】:

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

【讨论】:

  • 你认为static_cast&lt;double&gt;(4/3)会是什么?
猜你喜欢
  • 2018-01-11
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 2014-12-16
  • 1970-01-01
  • 2020-03-18
  • 2012-04-16
相关资源
最近更新 更多