简体   繁体   English

C编译器错误(浮点运算)?

[英]C compiler bug (floating point arithmetic)?

#include<stdio.h>

int main()
{
    double fract=0;
    int tmp;

    //scanf("%lf",&fract);
    fract=0.312;
    printf("%lf",fract);
    printf("\n\n");
    while(fract>0){
        fract*=(double)10;
        printf("%d ",(int)fract);
        fract-=(int)fract;
    }
    getch();
    return 0;
}

this code shoud have an output of: 312 该代码的输出应为:312

but somehing isn't going right.. i'm using devcpp 4.9.9.2 compiler... 但是有些事情是不对的。我正在使用devcpp 4.9.9.2编译器...

Kernighan & Plauger say, in their old but classic book "The Elements of Programming Style" , that: Kernighan&Plauger在其古老而经典的著作《编程风格的要素》中说:

  • A wise old programmer once said "floating point numbers are like little piles of sand; every time you move one, you lose a little sand and gain a little dirt". 一位明智的老程序员曾经说过:“浮点数就像一小堆沙子;每移动一个,就会丢掉一点沙子,并得到一点灰尘”。

They also say: 他们还说:

  • 10 * 0.1 is hardly ever 1.0 10 * 0.1几乎不会是1.0

Both sayings point out that floating point arithmetic is not precise. 两种说法都指出浮点运算并不精确。

Note that some modern CPUs (IBM PPC) have IEEE 754:2008 decimal floating point arithmetic built-in. 请注意,某些现代CPU(IBM PPC)内置了IEEE 754:2008十进制浮点算法。 If using the correct types, then your calculation will be exact. 如果使用正确的类型,则您的计算将是准确的。

Floating-point arithmetic is confusing, and not guaranteed to behave intuitively. 浮点算术令人困惑,并且不能保证直观地表现。

Here's a good reference document: What Every Computer Scientist Should Know About Floating-Point Arithmetic . 这是一个很好的参考文档: 每位计算机科学家都应该了解有关浮点算法的知识 It's a long document, because it's a complicated problem. 这是一个很长的文档,因为这是一个复杂的问题。

In summary: Don't use floating-point values if you are relying on exact values. 总结:如果您依赖精确值,请不要使用浮点值。

So you multiplied 0.3119999999999999999895916591441391574335284531116485595703125 by 1000 and truncated it and got 311? 因此,您将0.31199999999999999999999916591441391574335284531116485595703125乘以1000,并将其截断并得到311? I don't see where the problem is. 我看不出问题出在哪里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM