c++ - 如何在 C++ 中正确设置 double

标签 c++ visual-studio

我正在做一个项目,我需要做一些数学运算并给用户输出美元,所以我想让我的控制台告诉用户一个像$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/

相关文章:

c++ - libpq 中的查询流水线在哪里?

c# - Visual Studio 获取自动增量产品版本

c++ - CMake 相当于 Visual Studio 的 Property Sheets (.vsprops)

c++ - 'unused' 的初始化被 'goto label' 跳过 - 为什么我为 std::string 而不是为 int 获取它?

c++ - 卸载 CEF 崩溃

c++ - DLL 的 std::set_terminate 吗?

c++ - 在 std::map 中查找最接近或准确的键

c++ - QT QStackedLayout问题

visual-studio - VSTS 和 Azure 部署持续交付错误

c++ - 如何在 visual studio 的多个项目下的不同运行时环境中使用 CLR?