为什么两个大的双数相乘会得到错误的结果?
Why does multiplying two large double numbers give a wrong result?
这个双乘法(double)1000000007 * (double)11111111的输出应该以7结束(或者等于11111111077777777更精确)。但是我编写的这段代码输出的结果以6结尾(准确地说等于11111111077777776)。我不知道我做错了什么。如果有任何帮助就太好了。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setprecision(40) << (double)1000000007 * (double)11111111;
}
使用double
值进行乘法运算时,结果不精确。double
有一个固有的精度,它虽然相当准确,但不够精确,不能完全代表您的值。
我推荐阅读《What Every Computer Scientist Should Know About Floating-Point Arithmetic》
浮点数学不是精确的,它只是非常精确。我鼓励你在这里阅读:http://en.wikipedia.org/wiki/Floating_point
基本上没有足够的位来准确地表示这个数字,所以你会得到精度错误。
你没有做错什么。它与双精度的实现有关。如果您需要比double实现提供的精度更高的精度,那么肯定有一些库可用于"大数"操作。
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- Static_cast转换为错误的数据类型,但结果仍然正确?
- C++ 犰狳库中的sort_index()函数给出了错误的结果
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- 检查 n2 是否是 n1 的倍数后结果错误,但根本没有错误
- 为什么我的性能基准给了我错误的结果?
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 斐波那契检验(C++)的结果错误
- 在发布版本中划分两个双精度的结果错误
- 2D FFT后的图像结果错误
- 计算文本文件中的单个字母并打印结果 - 错误的输出 C++
- C++字符和 int 之间的转换,结果错误
- char*与std字符串的比较结果错误
- 斯波吉购物结果错误
- 超载"+"操作员,结果错误?
- 执行高斯消去程序时结果错误
- hash_djb2 PHP结果错误
- 按位操作比较结果错误
- 使用'if'语句和"<<"时的结果错误,'>>'运算符比较 3 个整数