Reputation: 305
Running the following code I expect to receive such an output:
Desired output:
Car Hours Charge
1 1.5 2.00
2 4.0 2.50
3 24.0 10.00
But the results comes out as follows:
Actual output:
Car Hours Charge
1 2 2
2 4 2.5
3 2e+01 10
Any suggestions that can guide me to use the correct floating point comparison and using setprecision correctly is welcome.
int main()
{
double hour[3];
double charge[3];
double sum_hour = 0;
double sum_charge = 0;
for (int i = 0; i < 3; i++)
{
cout<<"Enter the hours for car No. "<<i<<": ";
cin>>hour [i];
if (hour [i] <= 3)
{charge [i] = 2.00;}
if (hour [i] > 3 && hour [i] < 24)
{charge [i] = (2.00 + (ceil(hour [i] -3))*0.5);}
if (hour [i] == 24)
{charge [i] = 10.00;}
sum_hour = sum_hour + hour [i];
sum_charge = sum_charge + charge [i];
}
cout<<"Car"<<setw(10)<<"Hours"<<setw(10)<<"Charge"<<endl;
for (int i = 0; i < 3; i++)
{
cout<<i+1<<setw(10)<<setprecision(1)<<hour[i]<<setw(10)<<setprecision(2)<<charge[i]<<endl;
}
cout<<"TOTAL"<<setw(6)<<sum_hour<<setw(10)<<sum_charge<<endl;
}
Upvotes: 2
Views: 1039
Reputation: 215
You need function fixed
to make cout write digits when it got only '0'.
So use it like this:
cout << fixed;
cout<<i+1<<setw(10)<<setprecision(1)<<hour[i]<<setw(10)<<setprecision(2)<<charge[i]<<endl;
Upvotes: 1
Reputation: 16243
std::setprecision
by default sets the total number of significant digits that are shown (ie. including the ones before the decimal point).
To set the number of digits shown after the decimal point, use std::fixed
:
std::cout << std::fixed << std::setprecision(2) << 24.0;
will display :
24.00
Upvotes: 6