2013-08-22 60 views
0

我正在學習如何使用C++,並希望能夠幫助解決我遇到的問題。這是我寫的第一個程序,它計算消耗卡路里的數量和燃燒卡路里所需的距離。一切似乎都很好,我唯一的問題是輸出'total_calories'不顯示小數位。我希望它顯示1775.00而不是1775.我的輸入值是burgers_consumed = 3,fries_consumed = 1和drinks_consumed = 2。Beginning C++ - Decimal Place Issue

我得到的輸出是: 您攝入了1775卡路里。 你將不得不跑4.73英里來消耗這麼多的能量。

下面是代碼:

#include <iostream> 
using namespace std; 

int main() 
{ 
    const int BURGER_CALORIES = 400; 
    const int FRIES_CALORIES = 275; 
    const int SOFTDRINK_CALORIES = 150; 
    double burgers_consumed; 
    double fries_consumed; 
    double drinks_consumed; 
    double total_calories; 
    double total_distance; 


    //Get the number of hamburgers consumed. 
    cout << " How many hamburgers were consumed? "; 
    cin >> burgers_consumed; 

    //Get the number of fries consumed. 
    cout << " How many french fries were consumed? "; 
    cin >> fries_consumed; 

    //Get the number of drinks consumed. 
    cout << " How many soft drinks were consumed? "; 
    cin >> drinks_consumed; 

    //Calculate the total calories consumed. 
    total_calories = (BURGER_CALORIES * burgers_consumed) + (FRIES_CALORIES * fries_consumed) + (SOFTDRINK_CALORIES * drinks_consumed); 

    //Calculate total distance needed to burn of calories consumed. 
    total_distance = total_calories/375; 

    //Display number of calories ingested. 
    cout.precision(6); 
    cout << " You ingested " << total_calories << " calories. " << endl; 

    //Display distance needed to burn off calories. 
    cout.precision(3); 
    cout << " You will have to run " << total_distance << " miles to expend that much energy. " << endl; 
    return 0; 
} 

回答

2

你需要設置ios::fixed標誌,以便隨時查看尾隨零。

cout << " You ingested " << setiosflags(ios::fixed) << total_calories << " calories. " << endl; 

http://www.cplusplus.com/reference/ios/fixed/

當floatfield被設置爲固定的,浮點值使用定點表示法寫成:該值與小數部分一樣多的位數表示爲指定由精度字段(精度)和沒有指數部分。

由於BobbyDigital注意,你可能只是想在你的程序的開頭設定了這項政策,因爲這些設置是持久:

cout << setiosflags(ios::fixed); 

也不要忘記設置精度!

+0

可以指出,這樣的設置是持久的,可以設置一次,直到需要更改。我有一個簡單的'setMoney()'函數用於財務應用程序。 – ChiefTwoPencils

+0

是的,我會在我的答案中加上!謝謝。 –

+0

非常感謝Nemanja以及BobbyD,感謝您的幫助和鏈接。我瘋了試圖弄清楚,現在輸出結果是正確的。 –