如何正确设置C ++中的双精度 [英] How to properly set precision for doubles in C++
问题描述
我正在做一个项目,我需要做一些数学,并给用户输出美元,所以我想让我的控制台告诉用户一个答案像 $ 20.15
而不是
$ 20.153
。我使用设置精度函数:
cout<< setprecision(2);
,但不是让数字成为我想要的数字,而是转换成科学记数法。
I'm working on a project where I need to do some math and give the user output with dollars in it, so I would like to have my console tell the user an answer like $20.15
instead of $20.153
. I used the set precision function as such:
cout << setprecision(2);
, but rather than have the numbers become what I want them to be, they are converted into scientific notation.
输出大量数字,所以拥有 setprecision
这样的函数对我来说最适合使用。
I'm outputting a lot of numbers, so having a function like setprecision
would be best for me for ease of use.
如何正确地显示数字只有两个小数位,并且没有控制台给我科学记数法的数字?
How do I properly have the numbers displayed with only two decimal places and not have the console give me numbers in scientific notation?
感谢
Nathan
编辑:
这是我的代码的一部分I' m有问题:
Here is the part of my code I'm having problems with:
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;
}
显然有更多的东西,但这是我需要帮助。 / p>
Obviously there's more to it, but this is what I need help with.
推荐答案
要解决这个问题,你应该使用cout的固定浮点表示法。您可以在此处找到更多信息。
To fix that, you should use fixed floating-point notation for cout. You can find more info here.
尝试addind cout<<固定
到您的代码,如下面的代码。要将精度设置为 2
,可以使用 precision
属性。
Try addind cout << fixed
to your code, like the code below. To set the precision to 2
, you can use the 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 ++中的双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!