为什么两个大的双数相乘会得到错误的结果?

Why does multiplying two large double numbers give a wrong result?

本文关键字:结果 错误 两个 为什么      更新时间:2023-10-16

这个双乘法(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实现提供的精度更高的精度,那么肯定有一些库可用于"大数"操作。