【问题标题】:How to set the output precision to 2 decimal places in C++?如何在 C++ 中将输出精度设置为小数点后 2 位?
【发布时间】:2015-10-08 01:01:35
【问题描述】:

我想将输出精度全局设置为小数点后 2 位。

我已经尝试使用iomanipsetprecision,但是我不断得到带有“e”的输出。

这是我的示例代码:

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    double pay=16.78;
    double hours;
    double total;

    cout.precision(2); 

    cout << "Please enter how many hours you worked : " << endl;
    cin >> hours;

    total=hours*pay;

    cout << "You earned: " << total << endl;
}

【问题讨论】:

标签: c++ decimal precision


【解决方案1】:

我不熟悉“cout.precision(2)”。如果我希望我的输出有 4 个有效数字,我会使用 std::setprecision(4)。

【讨论】:

    【解决方案2】:

    你可以这样使用:

    double pay = 393.2993;
    std::cout << std::fixed << std::setprecision(2) << pay;
    

    您需要包含 iomanip 才能使其正常工作。

    #include <iomanip> 
    

    【讨论】:

      【解决方案3】:

      如果你的 e 是正值,你不能骑他们,因为你的值太大了。这段代码

      std::cout << std::setprecision(3) << 3e45;
      
      //output
      3e+45
      

      如果是负数,说明你的精度不够。像下面的代码

      std::cout << std::setprecision(3) << 3e-45; //
      
      //output
      3e-45
      

      一个简单的方法是使用 std::fixed

      std::cout << std::fixed << std::setprecision(3) << 3.63e-2;
      
      //output
      0.036
      

      但是你对 std::fixed 的缺点是它在最后一个非零数字之后显示零,直到它达到你之前设置的 setprecision qunatity。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 2013-12-09
        • 1970-01-01
        • 2011-01-19
        • 2011-10-03
        相关资源
        最近更新 更多