当乘以10的倍数时,失去双精度 [英] Losing Double Precision when multiplying by multiple of 10

查看:172
本文介绍了当乘以10的倍数时,失去双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码

int main(){

double d;
cin>>d;

while(d!=0.00)
{
    cout<<d<<endl;
    double m = 100*d;
    int n = m;
    cout<<n<<endl;
    cin>>d;
}

return 0;}

输入20.40 for d,n的值为2039而不是2040.
我尝试用 int n替换 int n = m =(int)m 但结果是一样的。
有任何方法来解决这个问题。提前感谢。

When I enter the input 20.40 for d the value of n comes out to be 2039 instead of 2040. I tried replacing int n = m with int n = (int) m but the result was the same. Is there any way to fix this. Thanks in advance.

推荐答案

您的代码会截断m,但您需要四舍五入。包括 cmath 并使用 int n = round(m)

Your code truncates m but you need rounding. Include cmath and use int n = round(m).

这篇关于当乘以10的倍数时,失去双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆