2012-01-25 44 views
0

我剛開始學習C++,並且一直在使用float和double值。下面是兩個代碼片段,這些代碼片段似乎在做同樣的事情,但會給出不同的結果。我錯過了什麼?有人可以解釋第一個代碼必須得到與第二個代碼不同的結果的精度錯誤。爲什麼這兩個代碼片段會產生不同的結果? (浮點數,雙精度)

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    const float f = 0.1; 
    const double d = 0.1; 
    int counter = 0; 

    for(counter; ((double)counter * f - (double)counter * d) < 0.34; counter++) {} 

    cout << "Iterations = " << counter << "\n" ; 

    system("pause"); 
    return 0; 
} 


int main (int argc, const char * argv[]) 
{ 
    float time_f = 0.1;  
    double time_d = 0.1; 
    float total_f = 0; 
    double total_d = 0; 
    int count=0; 
    double difference = 0; 
    while (true) { 
     total_d = count * time_d; 
     total_f = count * time_f; 
     if(total_f - total_d >= 0.34){ 

      break; 
     } 
     count++; 

    } 
    std::cout << count << "\n"; 
    system("pause"); 
} 

我已經改變了我對float和double但價值沒有區別之間循環條件的演員。

+1

推薦閱讀:http://floating-point-gui.de/ –

+0

http://docs.oracle.com/cd/E19957- 01/806-3568/ncg_goldberg.html –

回答

2

floatdouble都有一個有限表示,這意味着它們具有一系列的分離值,而不僅僅是任何實數值。在 特別是,在你的榜樣,0.1有任何現代機器,我知道(所有的使用基本 這是2在執行功率— 0.11/5 * 1/2上沒有確切的浮點 表示,並沒有什麼這是一個除非基數是5的倍數,否則1/5的倍數可以具有有限的表示)。

其結果是,無論是floatdouble具有相同的基礎 表示(通常不是這種情況),否則會有作爲 一旦count是從0

此通常的參考不同的差主題是 「什麼 每個計算機科學家都應該知道浮點數 算術」。直到你閱讀並理解了(或至少知道了這個暗示)它,你纔不應該碰機浮點 點。

0

您還沒有鑄造計數這裏翻番:

total_d = count * time_d; 
total_f = count * time_f; 

另一件事,這些循環將永遠不會結束,因爲兩個減法操作數具有相同的值:S

1

兩個代碼段之間的區別是在投。 counter * f被鑄造爲在第一個片段中加倍,並在第二個片段中存儲爲浮點變量。

下面是它如何可能看起來像一個例子:

#include <stdio.h> 

int main(int argc, char* argv[]) 
{ 
    const float f = 0.1; 
    const double d = 0.1; 
    int count = 0; 

    for(count; (double)(count * f) - (double)(count * d) < 0.34; count++); 

    printf("Iterations = %d\n", count); 
    count = 0; 

    while (true) 
    { 
     double total_d = count * d; // is equal to (double)(count * d) 
     double total_f = count * f; // is equal to (double)(count * f) 
     if (total_f - total_d >= 0.34) 
      break; 
     count++; 
    } 
    printf("Iterations = %d\n", count); 

    return 0; 
} 
相關問題