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

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


请帮忙!

最佳答案

您所看到的是输出流的默认精度为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的调用指定小数点后的位数。

我不确定您实际上想要什么格式,因为您没有说。但是这些功能以及亲戚应该可以让您获得所需的结果。

关于c++ - 双重乘法正在四舍五入,我不知道如何解决,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21496557/

10-12 20:35