cout输出怎么控制几位小数,如何在C ++中将输出精度设置为两位小数?

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

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

This is my example code:

#include

#include

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;

}

解决方案

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

A simple way will be to use std::fixed

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

//output

0.036

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值