问题描述
我一直在彻底寻找为什么会发生这种情况的正确解释,但仍然不太明白,所以如果这是重新发布,我深表歉意.
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
我似乎无法用任何其他号码复制此行为.也就是说,将 4.10 替换为该格式中的任何其他数字,输出是正确的.
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.
谢谢!
推荐答案
4.1 不能用 double
精确表示,它可以用更小的东西来近似:
4.1 cannot be exactly represented by a double
, it gets approximated by something ever so slightly smaller:
double x = 4.10;
printf("%.16f
", x); // Displays 4.0999999999999996
所以 j
会比 410 稍微小一点(即 409.99...).转换为 int
会丢弃小数部分,因此得到 409.
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.
(如果您想要另一个表现出类似行为的数字,您可以尝试 8.2、16.4 或 32.8...看到模式了吗?)
(If you want another number that exhibits similar behaviour, you could try 8.2, or 16.4, or 32.8... see the pattern?)
必填链接:每个计算机科学家都应该了解的内容浮点运算.
这篇关于为什么这种 double 到 int 的转换不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!