c++11之cout

C++中setprecision函数的用法

C++中,想要保留数据的有效位数,需要用到setprecision()/cout.precision()函数。 具体用法如下:
1、用setprecision()/cout.precision()函数都需要加上头文件:#include 。
其中io代表输入输出,manip是manipulator(操纵器)的缩写,它主要是对cin,cout之类的一些操纵运算子,比如setfill,setw,setbase,setprecision等等。它是I/O流控制头文件,就像C里面的格式化输出一样。

#include <iostream>     
#include<iomanip>//需要加上头文件     
using namespace std;     
int main()
{
	double a = 1.22023145, b = 0.123655;
	return 0;
}

2、使用setprecision()/cout.precision()之后,如果不在修改精度,则之后所有的数据输出都是按照设置的精度来输出。

#include <iostream>
#include<iomanip>
using namespace std;


int main()
{
	double a = 1.22023145, b = 0.123655,c=2.2;
	cout.precision(3);
	//cout << setprecision(3);这里和用上面的那句程序效果是一样的。
	cout << a << endl;//这里是3位有效数字,输出1.22
	cout << b << endl;//输出0.123
	cout << c << endl;//输出2.2
	return 0;
}

输出结果:

1.22
0.124
2.2

可以看到当你设置输出的有效位数之后,之后如果不改变输出格式,会一直用你设置的格式输出。

3、想要保留n为小数,需要加上cout.setf(ios::fixed); 或者cout << fixed或者cout<<setiosflags(ios::fixed) ;他们三个都是设置输入输出流用浮点数表示,再此过程中需要进行四舍五入。

#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
	double a = 1.22023145, b = 0.123655,c=2.2;
	
	//下面两行代码的作用一样,设置三位有效位数
	cout.precision(3);
	//cout << setprecision(3);
	
	//下面三行代码的作用一样。
	cout.setf(ios::fixed);
	//cout<<setiosflags(ios::fixed);
	//cout << fixed;
	
	cout << a << endl;//这里四舍五入,输出1.220
	cout << b << endl;//这里四舍五入,输出0.124
	cout << c << endl;//这里小数位数不够,需要补0,输出2.200
	return 0;
}

输出结果:保留三位小数,过程要进行四舍五入,位数不够的后面补0;

1.220
0.124
2.200

4、在输出的正数前面加上+号,需要用到cout << showpos或者 cout.setf(ios::showpos)或者cout << setiosflags(ios::showpos);

#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
	double a = 1.22023145, b = -0.123655,c=2.2;
	
	//下面三行的代码作用一样,都是使输出的数据前加上+号,负数除外;
	cout << setiosflags(ios::showpos);
	//cout << showpos << endl;
	//cout.setf(ios::showpos);
	
	cout.precision(3);
	//cout << setprecision(3);
	
	cout.setf(ios::fixed);
	//cout<<setiosflags(ios::fixed);
	//cout << fixed;
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
	return 0;
}

输出结果:

+1.220
-0.124
+2.200

原文链接:https://blog.csdn.net/weixin_44533275/article/details/107893624

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值