C++浮点数输出精度设置(刷题遇到)

版权声明:本博客为博主原创文章,未经博主允许,禁止转载,谢谢合作。 https://blog.csdn.net/weixin_43971252/article/details/87747846

注:在iomanip头文件里

1. 有效数据位数设置

单独使用cout<<setprecision(n)来设置,n为有效数据的位数。注意:cout<<不要丢。

2.小数点有保留几位

cout<<setprecision(n)和以下几种中的其中一种一起用,注意:这里的n为小数点保留n位。
cout<<fixed;
cout.setf(ios::fixed);
cout<<setiosflags(ios::fixed);

//vs2019运行的案例: 题目:hduoj2009

#include<iostream>
#include<cmath>
#include<iomanip> 
#include<cstdlib> 

using namespace std;

//思路:输入数列的第一项和总项数。之后根据项数来求和
//知识点:sqrt,pow库函数使用,浮点数输出定点小数
//注意:先求和,在开平方根
int main()
{
	double arr, sum;
	int n;

	while (cin >> arr >> n) {
		for (sum = 0.0; n--; arr = sqrt(arr))
			sum += arr;
		cout << setprecision(2); //设置有效数据为多少位
		cout << sum << endl;
		cout << setprecision(2) << setiosflags(ios::fixed);//设置小数点后两位
		cout << sum << endl;
	}

	system("pause");
	return 0;
}

输出:

猜你喜欢

转载自blog.csdn.net/weixin_43971252/article/details/87747846