Why does this double to int conversion not work?(为什么这种 double 到 int 的转换不起作用?)
问题描述
我一直在彻底寻找为什么会发生这种情况的正确解释,但仍然不太明白,所以如果这是重新发布,我深表歉意.
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 的转换不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这种 double 到 int 的转换不起作用?


基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01