gpt4 book ai didi

c++ - 为什么 double 和 long double 在下面的程序中给出不同的答案

转载 作者:行者123 更新时间:2023-11-28 06:09:50 26 4
gpt4 key购买 nike

此代码正在计算定义为的系列的第 N 项Tn+2=(Tn+1)^2+Tn,其中第一项和第二项在代码中作为 a 和 b 给出。

#include<iostream>
#include<string>
using namespace std;
int main()
{
int a,b,n;
char ch[100];
cin>>a>>b>>n;
long double res[3];
res[0]=a,res[1]=b;
for(int i=n-2;i>0;i--)
{
res[2]=res[1]*res[1]+res[0];
res[0]=res[1];
res[1]=res[2];
}
sprintf(ch,"%.0Lf",res[2]);
cout<<ch;
return 0;
}

输入:0 1 10

输出:

84266613096281242861568        // in case of double res[3];

84266613096281243385856 // in case of long double res[3];

correct output : 84266613096281243382112

因为它超出了整数范围,所以我使用了double/long double。

但问题是我得到了 double 和 long double 的不同输出,而中间值的小数点后没有非零数字,所以我猜不应该有任何四舍五入。

最佳答案

while none of the intermediate values are having non zero digit after decimal point, so there should not be any rounding off, I guess.

这个假设完全错误。 double 等所有 float 都存储为

mantissa * 2^exponent

尾数和指数的位数都是有限的。所以 float 可以存储固定数量的有效数字(对于转换为十进制表示的 double,通常为 16 位左右)。如果一个数字在小数点前有更多的数字,则会发生四舍五入,总的四舍五入误差越大,您需要“忘记”的数字越多。

如果您想了解更多详细信息,最常见的浮点实现遵循 IEEE floating point standard .

关于c++ - 为什么 double 和 long double 在下面的程序中给出不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31502044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com