如何在C++中正确设置双精度

How to properly set precision for doubles in C++

本文关键字:设置 双精度 C++      更新时间:2023-10-16

我正在做一个项目,我需要做一些数学运算并为用户提供带有美元的输出,所以我想让我的控制台告诉用户一个像$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 使用固定的浮点表示法。您可以在此处找到更多信息。

尝试将cout << fixed添加到代码中,如下面的代码所示。若要将精度设置为 2 ,可以使用 precision 属性。

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;
     }
}

Iostreams是格式化浮点值的痛苦。但是,为什么要使用浮点来表示货币值呢?您应该存储整数便士(或十分之一便士),因为尽管您不是以整数美元来衡量,但您的值实际上是固定点的。而且你真的不需要浮点带来的麻烦。然后,您可以将值的全部和"部分"部分分别流式传输"(使用 /% !),作为整数,中间有一个'.'

同时,请尝试std::fixed .

弊,看着纯粹主义者发疯......

    double time;  //Only want two decimal places.
    double timeCon = time * 100.0;  //Pull out the two decimals I want.
    int timeCut = timeCon;  //Cut all decimal values.
    double timeRevert = timeCut / 100.0;  //Laugh.
    cout << timeRevert << endl;  //Watch heads explode.