问题及代码:
*问题描述:用公式求PI的近似值。
*程序输出:π的近似值。
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float P,p=0,i=1,j=1;
while(fabs(1/i)>1e-5)
{
p=p+j/i;
i=i+2;
j=-j;
}
P=4*p;
cout<<"π的近似值为:"<<P<<endl;
return 0;
}
运行结果:
知识点总结:简单的循环结构,这次根据题目的要求,运用了while循环,简单方便。学会了根据题目的不同运用for循环和while循环的方法。也学会了c++中数学库函数<cmath>的运用。
学习心得:拿到题目不能盲目上手,需要根据题目的条件选择合适的方法,方能事半功倍。