如何在C ++中将输出精度设置为2位小数?

时间:2015-10-08 01:01:35

标签: c++ decimal precision

我想全局将ouptut精度设置为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;
}

3 个答案:

答案 0 :(得分:0)

如果你的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。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以使用以下内容:

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

您需要包含iomanip才能实现此功能。

#include <iomanip>