[英]double multiplication is getting rounded, and i don't know how to fix it
我的代碼將我的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
的調用指定小數點后的位數。
我不確定您實際上想要什么格式,因為您沒有說。 但是這些功能以及親戚應該可以讓您獲得所需的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.