双倍乘法正在四舍五入,我不知道如何解决它

时间:2014-02-01 09:57:24

标签: c++

我的代码将我的双值四舍五入,我将两个双倍相乘,然后将其调整为整数值。有人可以帮忙吗?

cout << "This program will determine the water needs for "
        "a refugee camp based on the number of refugees, "
        "daily water needs, and the existing water supplies."
        << endl
        << "Please enter the number of refugees: " << endl;

double NumOfRefugees = 0;
cin >> NumOfRefugees;

cout << "Please enter the daily water needs for each person "
        "(in the range 7.5 to 15.0 liters per day.): " << endl;

double DailyNeedsPerPerson = 0;
cin >> DailyNeedsPerPerson;

if (DailyNeedsPerPerson < 7.5 || DailyNeedsPerPerson > 15.0)
{
    cout << "The entered value is not within a reasonable range as specified in "
            "the Sphere Project Humanitarian Charter. The program will now end.";
    return 1;
}

double TotalDailyDemand = NumOfRefugees * DailyNeedsPerPerson;

cout << "The total demand is " << TotalDailyDemand << endl;

例如,当我输入15934和9.25时,我的代码输出:

This program will determine the water needs for a refugee camp based on the number of refugees, daily water needs, and the existing water supplies.
Please enter the number of refugees: 
15934
Please enter the daily water needs for each person (in the range 7.5 to 15.0 liters per day.): 
9.25
147390
The total demand is 147390

请帮忙!

1 个答案:

答案 0 :(得分:4)

您看到的是输出流的默认精度为6位数的结果。

因此,您需要对输出流应用一些格式,以便能够看到超过默认的6位数。例如:

#include <iostream>

int main()
{
    double x = 15934.0;
    double y = 9.25;
    double z = x*y;

    std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
    std::cout.precision(2);
    std::cout << z;
}

<强>输出

147389.50

setf的调用用于指定小数点后指定位数的固定浮点格式。对precision的调用指定了小数点后的位数。

我不确定你真正想要的格式,因为你没有说。但是这些功能和亲戚应该可以让你得到你想要的结果。