C++ 控制cout输出的小数位数

注:以下两种方法都用到头文件#include<iomanip>

方法一:

使用setprecision(n)与setiosflags(ios::fixed)合用,可以控制小数点右边的数字个数

setprecision(2)的意思就是小数点输出的精度,即输出小数点右边的数字的个数为2

cout<<fixd<<setprecision(2)<<Sum;//输出一个右对齐的小数点后两位的浮点数

方法二:

C++中的cout.setf()、cout.precision(),ostream成员函数里面的,也可以用输出流操作符来控制;

	1. #include<iostream>
	2. #include<iomanip>
	3. using namespace std;
	4. int main() {
	5.     double a, b, c;
	6.     float d;
	7.     a = 3.1415926535;
	8.     b = 0.3422342344;
	9.     c = 0.3422302344;
	10.     d = 1.2321435345;
	11.     cout << "默认输出" << endl;
	12.     cout << "a=" << a << endl;
	13.     cout << "b=" << b << endl;
	14.     cout << "c=" << c << endl;
	15.     cout << "d=" << d << endl;
	16.     //保留小数点后n位小数
	17.     //方法一
	18.     cout << fixed;
	19.     cout << "保留2位小数" << endl;
	20.     cout << "a=" << setprecision(2) << a << endl;//保留2位小数,3.14
	21.     cout << "保留3位小数" << endl;
	22.     cout << "a=" << setprecision(3) << a << endl;//保留3位小数,3.142,四舍五入
	23.     //或
	24.     cout << "保留4位小数" << endl;
	25.     cout << "a=" << fixed << setprecision(4) << a << endl;//保留4位小数,3.1416,四舍五入
	26.     //方法二
	27.     /*cout << fixed;*///方法二可以不加这个
	28.     cout << "保留2位小数" << endl;
	29.     cout.precision(2);//保留2位小数,可以不加cout<<fixed;
	30.     cout << "a=" << a << endl;//3.14
	31.     cout << "b=" << b << endl;//0.34
	32.     cout << "保留4位小数" << endl;
	33.     cout.precision(4); //保留3位小数,可以不加cout << fixed;
	34.     cout << "a=" << a << endl;//3.1416
	35.     cout << "b=" << b << endl;//0.3422
	36.     return 0;
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值