我正在开发一个程序,它根据用户输入的值输出在汽油上花费的总金额。我希望它输出一个带 2 位小数的值,但程序四舍五入而不是输出总数应该是什么。我是初学者,不知道为什么它不能正常工作。
double gasPrice = 3.87;
double gallonsPumped = 0;
cout<<"How many gallons of gasoline (Diesel) were purchased today:"<<endl;
cin>>gallonsPumped;
int finalGasPrice = gasPrice*gallonsPumped;
cout<<endl;
if (gallonsPumped >= 1)
{
cout<<endl<<"The total cost for gasoline today was $"<<finalGasPrice<<"."<<endl;
}
else
{
cout<<"No money spent on gasoline today.";
}
最佳答案
int 类型是整数 - 即没有小数位,因此乘法向下舍入到最接近的整数。
您想使用 float 或 double :
double finalGasPrice = gasPrice*gallonsPumped;
要使输出格式准确显示小数点后两位数,您可能需要使用类似以下内容的内容:
cout << setiosflags(ios::fixed) << setprecision(2) << finalGasPrice;
关于c++ - 使用 "double"输出带两位小数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10405841/