为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
Why typecasting a double to int seems to round it after 16th digit?
//g++ 5.4.0
#include <iostream>
int main()
{
std::cout << "Hello, world!n";
std::cout << (int)0.9999999999999999 << std::endl; // 16 digits after decimal
std::cout << (int)0.99999999999999999 << std::endl; // 17 digits after decimal
}
输出:
Hello, world!
0
1
为什么会这样?
0.99999999999999999
最准确的表示是1.0
。1(0.9999999999999999
最准确的表示是0.999999999999999888977697537484
。
1( 在 64 位双精度IEEE754浮点表示。
由于没有舍入,只有截断,因此当转换为整数类型时,一个给出1
,另一个给出0
。
值 0.99999999999999999(小数点后 17 位数字(的最准确浮点表示形式正好是 1.0。
值 0.99999999999999999(小数点后 16 位数字(的最准确浮点表示形式小于 1.0。
转换为 int 会将 1 截断为 0,将另一个截断为 1。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 计算十进制 c++ 之后的数字
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何在向量中某个数字之后重新计算进程
- 预期输出之后的所有这些数字是多少
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- C++ 在地板函数之后以十六进制打印数字
- 在每个偶数特定数字之后,插入向量中
- 如何在C ++中打印特定位数的位数?例如,总共打印8位数字(小数点之前+之后的组合)
- C :Bool方法在COUT语句之后返回意外数字
- 小数点之后,如何指定有多少个数字
- C 如何在文件中的特定字符串之后获取数字
- std::queue::size() 可以在 size() == 0 的 pop() 之后返回一个巨大的数字
- 如何从 9 和 90 中提取 2.9 和 2.09,即获取数字等于最大编号的小数部分.二分位数之后的数字
- 默认值仅适用于 8 和 9.之后,它使用第一个数字并将其视为 1,2,3
- 在waitpid()之后来自WTERMSIG宏的异常信号数字
- 如何在第 "." 点之后将数字放入数组中
- 仅读取文本文件中的数字并存储在数组中.之后,读取第一行来存储在数组中
- 在c++中截断数字(点之后)
- 如何在读取文本文件时跳到每行最后一个数字之后的下一行