简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM