C++中cout.setf(ios_base::fixed, ios_base::floatfield);

在练习c++primerplus这本书上的程序时,看到一句话“ios_base::fixed, ios_base::floatfield是通过包含iostream来提供的常量”比较疑惑,就多试了几次。

源程序如下:

#include
int main()
{
	using namespace std;
	cout.setf(ios_base::fixed, ios_base::floatfield);
	float tub=10.0 / 3.0;
	double mint = 10.0 / 3.0;
	const float million = 1.0e6;
	cout << "tub = " << tub;
	cout << ",a million tubs = " <C++中cout.setf(ios_base::fixed, ios_base::floatfield);_第1张图片

 当去掉cout.setf(ios_base::fixed, ios_base::floatfield);一句后,结果如下:

C++中cout.setf(ios_base::fixed, ios_base::floatfield);_第2张图片

 百度后得知ios_base::fixed是设置cout为定点输出格式;ios_base::floatfield是设置输出时按浮点格式,小数点后有6位数字。所谓定点输出即小数点位置固定(数值范围有限),详情可参考(18条消息) 数据格式(定点表示 浮点表示)_鲸临于空-CSDN博客_定点表示,百度后得知还可用setprecision(int)来设定小数点后具体几位,要加上#include ,修改后代码如下:

#include 
#include
int main()
{
	using namespace std;
	float tub=10.0 / 3.0;
	double mint = 10.0 / 3.0;
	const float million = 1.0e6;
	cout << "tub = " << tub;
	cout << ",a million tubs = " << fixed << setprecision(3) << million * tub;
	cout << ",\nand ten million tubs = ";
	cout << 10 * million * tub << endl;
	cout << "mint = " << mint << " and a million tubs = ";
	cout << million * mint << endl;
	return 0;
}

输出结果如下C++中cout.setf(ios_base::fixed, ios_base::floatfield);_第3张图片

 

你可能感兴趣的:(ios,c++)