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 的转换不起作用?


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30