从C ++开始 - 小数位置问题

时间:2013-08-22 07:34:42

标签: c++ decimal

我正在学习如何使用C ++,并希望能帮助解决我遇到的问题。这是我写的第一个程序,它计算燃烧的卡路里数和燃烧卡路里所需的距离。一切似乎都很好,我唯一的问题是输出'total_calories'不显示小数位。我希望它显示1775.00而不是1775.我的输入值是burgers_consumed = 3,fries_consumed = 1,drink_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;
}   

1 个答案:

答案 0 :(得分:2)

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

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

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

  

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

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

 cout << setiosflags(ios::fixed);

不要忘记设置精度!