2015-10-14 45 views
1

爲什麼這段代碼的結果是錯誤的?我無法解決這個問題。爲什麼(1.1-1.0)* 10不是1.0?

#include <stdio.h> 
int main(int argc, char **argv) 
{ 
if ((1.1 - 1.0)*10.0 - 1.0 == 0.0) 
    printf("True"); 
else 
    printf("False"); 
return 0; 
} 
+0

重複:http://stackoverflow.com/q/588004 –

+0

因爲浮點是魔鬼。我以前說過,我會一直說,直到人們明白。 – ShadowRanger

+0

1.1並不完全是理性數字11/10。它相當於[二元理性](https://en.wikipedia.org/wiki/Dyadic_rational),其值接近11/10。 – chepner

回答

1

但是,這可以作爲你想:

int main(int argc, char **argv) 
{ 
    float x,y; 
    x=0.0; 
    y=0.0; 

    x=1.1 - 1.0; 
    x=x*10.0; 
    x=x-1.0; 

    if ( x==y) 
     printf("True"); 
    else 
     printf("False"); 
    return 0; 
} 
+0

我不認爲這有效。你所做的只是用一系列的賦值來替換單個表達式。 – chepner

+0

請編譯並運行。 – BobRun

0

大多數double數學使用binary floating point表示。所以1.1不是正好可代表 - 只是接近它。考慮使用volatile來防止編譯器優化。

#include <stdio.h> 
int main(void) { 
    volatile double wpw = 1.1; 
    volatile double one = 1.0; 
    volatile double ten = 10.0; 
    printf("%.20e\n", wpw); 
    printf("%.20e\n", wpw - one); 
    printf("%.20e\n", (wpw - one) * ten); 
    printf("%.20e\n", (wpw - one) * ten - one); 
    return 0; 
} 

並在下面輸出。 1.1 - 1.0只有0.1

1.10000000000000008882e+00 
1.00000000000000088818e-01 
1.00000000000000088818e+00 
8.88178419700125232339e-16 
相關問題