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

double multiplication is getting rounded, and i don't know how to fix it

本文关键字:何解决 解决 我不知道 四舍五入      更新时间:2023-10-16

我的代码正填补我的双重值,我要乘以两个双打,然后将其缩小到整数值。有人可以帮忙吗?

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的呼叫指定小数点之后多少位数字。

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