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

标签 c++

我的代码将我的 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/

相关文章:

c++ - 我如何使用带有 "this"的 const 函数

c++ - 为什么我不能继承虚拟基的构造函数?

c++ - 尽管使用 unique_ptr 内存泄漏

c++ - Dependency Walker 在函数名称后显示 @x

C++ filesystem 系统找不到指定的路径

C++ 类 : create copy of "this" class within member function

c++ - 将多个 MP3 轨道合并为一个轨道

c++ - c++ linux 中的静态链接使用: do I need to recompile everything each time I change library?

c++ - 泰勒级数在 sin(90) 和 cos(120) 之后得到 nan

c++ - 初始化中模板转换运算符类型推导的规则是什么?