一个学妹问的一道c语言题目
标题单位圆的面积为π,因此可以通过求单位圆面积的近似值来求π的近似值。考虑将单位圆沿x轴分成n份,从而求得n个梯形的面积和作为单位圆的一个近似值;
再将单位圆分成2n份,从而求得2n个梯形的面积和作为单位圆的另一近似值。此过程可以一直持续下去,将单位圆分成4n份、8n份等等,当二次求得的近似值很接近时,可认为得到单位圆面积较精确的近似值。将下列程序补充完整,利用上述方法求π的近似值
#include <math.h>
#include <iostream>
using namespace std;
int main(){
const double epsilon = 1E-4;//这里我特意将极限写成负四次方,不然执行时间太长
int n = 2;
double dist_s = 1.0;//默认1
double pi = 0.0;
for (n; epsilon < dist_s; n ++ )
{ double x1 = 2.0/n;//高
cout << "x1 = " << x1 << endl;
double x2 = 2.0/(2*n);//高
cout << fixed<<"x2 = " << x2 << endl;
double s1 = 0.0;//x/n高度梯形的面积
double s2 = 0.0;//x/2n高度梯形的面积
cout << "n = " << n << endl;
for (double i = -1;i < 1;i = i + x1){
double h1 = 2*sqrt(1-pow(i,2));//上底
double h2 = 2*sqrt(1-pow(i + x1,2));//下底
s1 += (h1+h2)*x1/2.0;
}
cout << "s1 = " << s1 << endl;
for (double i = -1;i < 1;i = i + x2){
double h1 = 2*sqrt(1-pow(i,2));//上底
double h2 = 2*sqrt(1-pow(i + x2,2));//下底
s2 += (h1+h2)*x2/2.0;
}
cout << "s2 = " << s2 << endl;
dist_s = fabs(s1 - s2);
cout <<"dist =" << dist_s << endl;
}
cout << "pi = " << dist_s << endl;
}
codeblock中运行