0

我正在学习如何使用 C++,希望能帮助我解决我遇到的问题。这是我编写的第一个程序,它计算燃烧的卡路里数量和燃烧卡路里所需的距离。一切似乎都很好,我唯一的问题是输出“total_calories”不显示小数位。我希望它显示 1775.00 而不是 1775。我的输入值为 burgers_consumed = 3、fries_consumed = 1 和 Drinks_consumed = 2。

我得到的输出是:你摄入了 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;
}   
4

1 回答 1

2

您需要设置ios::fixed标志才能始终看到尾随零。

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

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

当 floatfield 设置为 fixed 时,浮点值使用定点表示法写入:该值由精度字段 (precision) 指定的小数部分中的位数表示,并且没有指数部分。

正如 BobbyDigital 所指出的,您可能只想在程序开始时设置此设置,因为这些设置是持久的:

 cout << setiosflags(ios::fixed);

不要忘记设置精度!

于 2013-08-22T07:42:14.767 回答