关于C++中cout.precision()的使用以及控制输出的小数位数.

在C++中可以使用cout.precison(val)来控制浮点数的输出精度,但并不是意味着仅使用cout.precison(val)可以控制输出结果的小数点位数,在此记录一下,就当做学习笔记。

下面先做一下简单的验证:

#include <iostream>
using namespace std;
int main()
{
	double x = 1.23456789;
	cout.precision(1);
	cout << "The first : " << x << endl;//输出设置位数为1的x 的值
	cout.precision(2);
	cout << "The second : " << x << endl;//输出设置位数为2的x 的值
	cout.precision(3);
	cout << "The third : " << x << endl;//输出设置位数为3的x 的值
	return 0;
}

输出结果为:

The first :1
The second :1.2
The third : 1.23

再将x的值改为0.002,结果如下:

The first :0.002
The second :0.002
The third : 0.002

从结果可以看出,cout.precision()是用来控制输出的有效数字的个数,而不能控制输出的小数位数
而要想控制输出小数点后的数字的位数,则可以这样对程序进行改进:

#include <iostream>
using namespace std;
int main()
{
	double x = 0.0023;
	cout.precision(1);
	cout << "1 : " <<fixed<< x << endl;//输出设置位数为1的x 的值
	cout.precision(2);
	cout << "2 : " <<fixed<< x << endl;//输出设置位数为2的x 的值
	cout.precision(3);
	cout << "3 : " <<fixed<< x << endl;//输出设置位数为3的x 的值
	system("pause");
	return 0;
}

输出结果为:

The first :0.0
The second :0.00
The third : 0.002

因此,使用cout.precision()能够控制输出的有效数字的个数,而不能控制小数点后的输出位数。
要想控制小数点后数字的输出位数,则可以使用下面的格式:

	cout.precision(val);  //val代表小数点后输出的小数位数
	cout << "The number is  : " <<fixed<< x << endl;    //`在输出前加上**fixed**则可实现
发布了17 篇原创文章 · 获赞 25 · 访问量 5663

猜你喜欢

转载自blog.csdn.net/qq_44894692/article/details/97265255