gpt4 book ai didi

c - 为什么下面的代码中不是 a==0 呢?

转载 作者:行者123 更新时间:2023-12-01 15:42:23 24 4
gpt4 key购买 nike

#include <stdio.h>
int main( )
{
float a=1.0;
long i;

for(i=0; i<100; i++)
{
a = a - 0.01;
}
printf("%e\n",a);
}

结果是:6.59e-07

最佳答案

这是一个二进制 float ,而不是十进制数 - 因此您需要预料到舍入误差。请参阅本文中的基本部分:

What Every Programmer Should Know About Floating-Point Arithmetic

例如,值0.01在二进制浮点型中没有精确的表示。要在样本中获得“正确”结果,您必须四舍五入或使用十进制浮点类型(请参阅 Wikipedia):

Binary fixed-point types are most commonly used, because the rescaling operations can be implemented as fast bit shifts. Binary fixed-point numbers can represent fractional powers of two exactly, but, like binary floating-point numbers, cannot exactly represent fractional powers of ten. If exact fractional powers of ten are desired, then a decimal format should be used. For example, one-tenth (0.1) and one-hundredth (0.01) can be represented only approximately by binary fixed-point or binary floating-point representations, while they can be represented exactly in decimal fixed-point or decimal floating-point representations. These representations may be encoded in many ways, including BCD.

关于c - 为什么下面的代码中不是 a==0 呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5816559/

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