Reputation: 280
My code is rounding my double values off, I'm multiplying two doubles, and it's roudning it off to an integer value. can someone help?
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;
For example, when I input 15934 and 9.25, My code outputs:
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
Please help!
Upvotes: 0
Views: 87
Reputation: 612963
What you are seeing is a result of the default precision of the output stream being 6 digits.
So, you need to apply some formatting to the output stream to be able to see more than the default 6 digits. For instance:
#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;
}
Output
147389.50
The call to setf
is used to specify fixed floating point formatting with a specified number of digits after the decimal point. The call to precision
specifies how many digits after the decimal point.
I'm not sure what formatting you actually want because you did not say. But these functions, and the relatives, should allow you to get the result that you desire.
Upvotes: 4