如何在C ++中将输出精度设置为2位小数? [英] How to set the output precision to 2 decimal places in C++?

查看:994
本文介绍了如何在C ++中将输出精度设置为2位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将ouptut精度全局设置为2个小数位.

I want to globally set the ouptut precision to 2 decimal places.

我已经尝试使用iomanipsetprecision,但是我一直在输出带有'e'的内容.

I already tried to use iomanip and setprecision, however I keep getting output with 'e' in it.

这是我的示例代码:

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

推荐答案

如果您的e为正值,则您不能使用它们,因为您的值太大.这段代码

If your e is a positive value, you cannot ride of them because your value is too large. This code

std::cout << std::setprecision(3) << 3e45;

//output
3e+45

如果它是负数,则您的精度不够.像下面的代码

If it's a negative number, your precision is not enough. Like the following code

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

//output
3e-45

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

A simple way will be to use std::fixed

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

//output
0.036

但是std :: fixed的缺点是它会在最后一个非零数字之后显示零,直到达到先前设置的setprecision数量为止.

But the disavantage you have with the std::fixed is it shows the zero after the last none-zero number until it reach the setprecision qunatity you set previously.

这篇关于如何在C ++中将输出精度设置为2位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆