计算π的值

计算π的值


使用π/4=1-1/3+1/5-1/7…这个公式求π的近似值,直到某一项的绝对值小于10-6为止。
样例:
输入

输出

3.141591
/*
使用π/4=1-1/3+1/5-1/7...这个公式求π的近似值,直到某一项的绝对值小于10-6为止。
*/
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main(void)
{
    
    
	int sign = 1;
	double pi = 0.0, n = 1.0, term = 1.0;
	while (fabs(term) >= 1e-6)
	{
    
    
		pi += term;
		n += 2;
		sign = -sign;
		term = sign / n;
	}
	pi *= 4;
	cout<<fixed<<setprecision(6)<<pi<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45830912/article/details/113148580