C++ 浮点数截取精度

C++ 中浮点数截取精度,代码如下:

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

int main()
{
	double pi = 3.1415926;
	cout << setprecision(3) << pi << endl; //有效位数为3位
	cout << setiosflags(ios::fixed) << setprecision(3) << pi << endl; //保留小数点后3位
	cout << ios::fixed << endl; //单独的数值是 8192

	double sqrt2 = 1.41375;/*1.414213562373095;*/
	stringstream ss;
	ss << setiosflags(ios::fixed) << setprecision(3) << sqrt2 << endl;
	ss >> sqrt2;
	cout << sqrt2 << endl;
	return 0;
}

采用`cout`输出会截断,但是查看存储的数值,还是存在偏差的小数。

猜你喜欢

转载自blog.csdn.net/jekcai/article/details/86069225
今日推荐