gpt4 book ai didi

c - C算术怎么会这么不精确呢?

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:52 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Floating point inaccuracy examples

在我的电脑上使用 g++ 我发现:

21*3.6 ==  75.60000000000000852651

这会破坏一个简单的循环。看这段代码:

  double incr=3.6;
double limit=21*3.6;
printf (" ¿%f == %.20f? \n", limit, limit);
for (double x=0.0; x<limit; x += incr) {
printf (" x %f < limit %f (dif = %.20f) \n", x, limit, limit-x);
}

及其输出:

 ¿75.600000 == 75.60000000000000852651? x=0.000000, limit=75.600000 (dif = 75.60000000000000852651) x=3.600000, limit=75.600000 (dif = 72.00000000000001421085) x=7.200000, limit=75.600000 (dif = 68.40000000000000568434) x=10.800000, limit=75.600000 (dif = 64.80000000000001136868) x=14.400000, limit=75.600000 (dif = 61.20000000000000994760) x=18.000000, limit=75.600000 (dif = 57.60000000000000852651) x=21.600000, limit=75.600000 (dif = 54.00000000000000710543) x=25.200000, limit=75.600000 (dif = 50.40000000000000568434) x=28.800000, limit=75.600000 (dif = 46.80000000000000426326) x=32.400000, limit=75.600000 (dif = 43.20000000000000284217) x=36.000000, limit=75.600000 (dif = 39.60000000000000142109) x=39.600000, limit=75.600000 (dif = 36.00000000000000000000) x=43.200000, limit=75.600000 (dif = 32.39999999999999857891) x=46.800000, limit=75.600000 (dif = 28.79999999999999715783) x=50.400000, limit=75.600000 (dif = 25.19999999999999573674) x=54.000000, limit=75.600000 (dif = 21.59999999999999431566) x=57.600000, limit=75.600000 (dif = 17.99999999999999289457) x=61.200000, limit=75.600000 (dif = 14.39999999999999147349) x=64.800000, limit=75.600000 (dif = 10.79999999999999715783) x=68.400000, limit=75.600000 (dif = 7.20000000000000284217) x=72.000000, limit=75.600000 (dif = 3.60000000000000852651) x=75.600000, limit=75.600000 (dif = 0.00000000000001421085)  

表示最后一次循环不应该被执行但是对于错误!

建议?

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