运行以下代码我希望收到这样的输出:
Desired output:
Car Hours Charge
1 1.5 2.00
2 4.0 2.50
3 24.0 10.00
但结果如下:
Actual output:
Car Hours Charge
1 2 2
2 4 2.5
3 2e+01 10
我们欢迎任何可以指导我使用正确 浮点 比较并正确使用 setprecision 的建议
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;
}
答案 0 :(得分:3)
std::setprecision
设置显示的有效位数总数(即包括小数点前的有效位数)。
要设置小数点后显示的位数,请使用std::fixed
:
std::cout << std::fixed << std::setprecision(2) << 24.0;
将显示:
24.00
答案 1 :(得分:1)
当只有'0'时,你需要函数fixed
来使cout写数字。
所以像这样使用它:
cout << fixed;
cout<<i+1<<setw(10)<<setprecision(1)<<hour[i]<<setw(10)<<setprecision(2)<<charge[i]<<endl;