2014-11-14 82 views
-5

這兩個程序的輸出爲什麼不同?我已經包含了代碼,以便您可以輕鬆查看並嘗試。任何人都可以解釋給我嗎?爲什麼這些程序以不同的順序執行相同的計算給了我不同的輸出?

#include <iostream> 
#include <iomanip> 
using namespace std; 

int main() { 
    float pi = 3.14159; 
    int r; 

    while (cin >> r) { 
     cout << "VOLUME = " << fixed << setprecision(3) 
      << pi*r*r*r*(4.0/3.0) << endl; 
    } 

    return 0; 
} 
#include <iostream> 
#include <iomanip> 
using namespace std; 

int main() { 
    float pi = 3.14159; 
    int r; 

    while (cin >> r) { 
     cout << "VOLUME = " << fixed << setprecision(3) 
      << (4.0/3.0)*r*r*r*pi << endl; 
    } 

    return 0; 
} 

如果我輸入1523第一個給我14797487059.353,這是正確的答案,但第二個給出了一個負數。

The 2 screens with the outputs this link include the 2 outputs the first one ir the right the second one is weird !

+0

該問題可能是浮點不精確。除非他沒有設定變量,否則任何事情都可能發生。你能發佈完整的程序嗎? – leetNightshade 2014-11-14 19:22:02

+0

@spartygw [見這裏](http://meta.stackoverflow.com/questions/262446/are-we-being-elitist-is-there-something-wrong-with-that/262455#262455)。如果你願意幫助他,花時間並通過編輯將問題轉換成適當的形狀。我的經驗是,當他們的問題擱置時,最好的學習效果是由noobs採取的。 – 2014-11-14 19:29:42

+0

第一個如果我嘗試1523它給我14797487059.353這是正確的一個 – 2014-11-14 19:44:57

回答

0

在你的屏幕截圖中的代碼是不是你已經張貼在這裏什麼。我建議,將來如果你需要幫助解決你遇到的問題,你可以發佈你遇到的問題 - 而不是完全不同的代碼。

在這種情況下,問題很簡單 - r*r*r太大而無法放入一個int中。您可以將r更改爲long long,此問題應該消失。或者,您可以使用您在此處發佈的兩個代碼塊中的任意一個,因爲它們都按照您的預期工作。

相關問題