gpt4 book ai didi

c - float 不精确

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

我很疑惑。我没有解释为什么这个测试在使用 double 数据类型时通过但在使用 float 数据类型时失败。考虑以下代码片段。

float total = 0.00;

for ( int i = 0; i < 100; i++ ) total += 0.01;

人们预计 total 为 1.00,但它等于 0.99。为什么会这样?我同时使用 GCC 和 clang 进行编译,两个编译器的结果相同。

最佳答案

试试这个:

#include <stdio.h>

int main(){
float total = 0.00;
int i;
for (i = 0; i < 100; i++)
total += 0.01;

printf("%f\n", total);

if (total == 1.0)
puts("Precise");
else
puts("Rounded");
}

至少在大多数机器上,您会得到“Rounded”的输出。换句话说,结果只是恰好足够接近,以至于当它被打印出来时,它被四舍五入,所以它看起来正好是 1.00,但实际上不是。将 total 更改为 double,您仍然会得到相同的结果。

关于c - float 不精确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18140849/

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