2012-08-08 113 views
3

有人可以解釋我爲什麼在C++中發生這樣的事情:如果我有爲什麼trunc(1)輸出爲0?

double tmp; 
...     // I do some operations with tmp 
         // after which it has to be equal to one 
cout << tmp;   // prints 1 
cout << trunc(tmp); // prints 0 
cout << trunc(tmp*10); // prints 9 

我用這對小數部分例如從數量的分離部分權:5.010 ...我想有0.010 ..所以我使用:

double remainder = tmp - trunc(tmp); 

我張貼整個代碼....與地板的建議不工作

short getPrecision(double num, short maxPrecision) { 

    // Retrieve only part right of decimal point 
    double tmp = fabs(num - trunc(num)); 
    double remainder = tmp; 

    // Count number of decimal places 
    int c = 0; 
    while (remainder > 0 && c < maxPrecision) { 
    tmp *= 10; 
    remainder = tmp - trunc(tmp); 
    c++; 
    } 
    return c; 
} 

當運行該功能例如具有5.1 remanider是0而不是1

+0

,你能否告訴我們的操作?因爲正如阿門的答案指出的那樣,有時雙重行動並不準確。 – quasiverse 2012-08-08 09:21:58

+0

嘗試在輸出值之前將精度設置爲17。 '<<'四捨五入(默認爲6位精度)。截斷和舍入給出不同的結果並不令人驚訝。 – 2012-08-08 09:28:14

+0

或者你可以嘗試輸出tmp - 1.它看起來像我tmp不一定是1。 – 2012-08-08 09:50:07

回答

6

一些計算它必須是一個後?那麼,它可能是0.99999999999999999。浮點運算並不精確,您應該始終考慮到這一點。

+0

那麼,0.(9)正好等於1 btw; P – SingerOfTheFall 2012-08-08 12:17:33

+0

@SingerOfTheFall:是的,但前提是有無數個9。但在電腦中,一切都是有限的:P – 2012-08-08 12:23:53

+0

只是在開玩笑;) – SingerOfTheFall 2012-08-08 12:41:19