gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:08:51 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com