为什么这个double到int转换不工作? [英] Why does this double to int conversion not work?

查看:111
本文介绍了为什么这个double到int转换不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在彻底寻找为什么会发生这种情况的正确解释,但仍然不能真正理解,所以如果这是一个转贴,我道歉。

  #include< iostream> 
int main()
{
double x = 4.10;
double j = x * 100;

int k =(int)j;

std :: cout<< k;
}

输出:409

以将此行为与任何其他数字复制。也就是说,将4.10替换为该表单中的任何其他数字,并且输出是正确的。



必须有一些低级转换东西,我不明白。



谢谢!

解决方案

4.1不能由 double ,它会被稍微小些的东西近似:

  double x = 4.10; 
printf(%。16f \\\
,x); // Displays 4.0999999999999996

因此 j 比410稍微小一点(即409.99 ...)。转换到 int 舍弃小数部分,所以你得到409。



(如果你想要另一个展示类似行为,你可以尝试8.2,或16.4,或32.8 ...看模式?)

义务链接:每个计算机科学家应该知道的浮点算术


I've been thoroughly searching for a proper explanation of why this is happening, but still don't really understand, so I apologize if this is a repost.

#include <iostream>
int main()
{
    double x = 4.10;
    double j = x * 100;

    int k = (int) j;

    std::cout << k;
 }

 Output: 409

I can't seem to replicate this behavior with any other number. That is, replace 4.10 with any other number in that form and the output is correct.

There must be some sort of low level conversion stuff I'm not understanding.

Thanks!

解决方案

4.1 cannot be exactly represented by a double, it gets approximated by something ever so slightly smaller:

double x = 4.10;
printf("%.16f\n", x);  // Displays 4.0999999999999996

So j will be something ever so slightly smaller than 410 (i.e. 409.99...). Casting to int discards the fractional part, so you get 409.

(If you want another number that exhibits similar behaviour, you could try 8.2, or 16.4, or 32.8... see the pattern?)

Obligatory link: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

这篇关于为什么这个double到int转换不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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