我正在做一个项目,我需要做一些数学运算并给用户输出美元,所以我想让我的控制台告诉用户一个像$20.15
这样的答案。而不是 $20.153
.我这样使用设置精度函数:
cout << setprecision(2);
,但不是让数字成为我想要的数字,而是将它们转换为科学记数法。
我输出了很多数字,所以有一个类似 setprecision
的函数最适合我的易用性。
如何正确地让数字只显示两位小数,而不是让控制台以科学记数法给出数字?
谢谢
内森
编辑:
这是我遇到问题的代码部分:
int main() {
cout << setprecision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
显然还有更多内容,但这正是我需要帮助的地方。
最佳答案
要解决这个问题,您应该为 cout 使用固定的浮点表示法。您可以找到更多信息 here .
尝试添加 cout << fixed
到您的代码,如下面的代码。将精度设置为 2
, 您可以使用 precision
属性(property)。
cout << fixed;
cout.precision(2);
完整代码如下:
using namespace std;
int main() {
cout << fixed;
cout.precision(2);
if (totalCostHybrid < totalCostNonHybrid) {
cout << "Hybrid car: " << endl;
cout << "Total cost: " << totalCostHybrid << endl;
cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
cout << "Total gas cost: " << gasCostHybrid << endl;
cout << "Non-hybrid car: " << endl;
cout << "Total cost: " << totalCostNonHybrid << endl;
cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
cout << "Total gas cost: " << gasCostNonHybrid << endl;
cout << "Hybrid is cheaper!" << endl;
}
}
关于c++ - 如何在 C++ 中正确设置 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35045643/