为什么 4.7 在 c 中是 4.6999999

Dev*_*eer -2 c mingw codeblocks floating-accuracy

'

#include <stdio.h>
#include <math.h>

int main(){  
        int i;  
        float num = 4.700;   
        for(i=1;i<5;i++){ 
              printf("%0.3f\tx%d\t\t=%d\n",num,(int)pow(10,i),(int)(num*pow(10,i)));
        }  
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

' 此代码将以下内容打印到控制台: '

4.7000   x10        =46  
4.7000   x100       =469  
4.7000   x1000      =4699  
4.7000   x10000     =46999
Run Code Online (Sandbox Code Playgroud)

' 这个结果与所有浮点值不一致

1.2000 打印出 ...120...1200 等等
1.8000 又是奇怪的

我在 Codeblocks 工作,我的问题是为什么有些浮点数会以这种方式做出反应?我缺少 C 或 mingw 编译器的一些基础知识吗?还是我的代码有问题?
感谢您的帮助,如果是重复问题,请见谅

Dav*_*rtz 5

这是有限精度表示的本质。当您尝试使用无法准确表示的数字时,就会发生这种情况。

有限精度小数也会发生同样的事情。如果使用六位数字,则只能将 1/3 表示为“0.333333”。但是现在 1/3 的 3 倍不会等于 1。您可以将 2/3 表示为“0.666667”,但现在 1/3 乘以 2 不会等于 2/3。

4.7 不能用二进制精确表示,就像 1/3 不能用十进制精确表示一样。使用最接近的可能表示,只是稍微小一点。