程序设计题目~~~c语言

来源:百度知道 编辑:UC知道 时间:2024/05/05 05:35:50
编写程序,用如下公式计算圆周率的近似值。
派=4-4/3+4/5-4/7+...
回答程序要计算多少项才能得到数值3.14,3.141,3.1415,3.14159。

我做了一个 告诉我我的答案对了没? 多谢阿

#include<stdio.h>
#include<math.h>
void main()
{
int e = 1;
double a=4;
while(fabs(a-3.14)>=1e-3)
{
a+=pow(-1,e)* 4/(1+2*e);
e++;
}
printf("要计算%d项才能得到数值3.14\n",e);

int f = 1;
double b=4;
while(fabs(b-3.141)>=1e-3)
{
b+=pow(-1,f)* 4/(1+2*f);
f++;
}
printf("要计算%d项才能得到数值3.141\n",f);

int g = 1;
double c=4;
while(fabs(c-3.1415)>=1e-3)
{
c+=pow(-1,g)* 4/(1+2*g);
g++;
}
printf("要计算%d项才能得到数值3.1415\n",g);

int h = 1;
double d=4;
while(fabs(d-3.14159)>=1e-3)
{
d+=pow(-1,h)* 4/(1+2*h);
h++;
}
printf("要计算%d项才能得到数值3.14159\n",h);

}

while(fabs(a-3.14)>=1e-3)
这种式子明显是错误的 精度不同是判断错误!

不说你的代码正确与否,解决问题的方法欠佳。
3.14,3.141,3.1415,3.14159应当被看作是输入参数,而不应当作为常量写到代码段里头。要照你这么做,给你一百多个不同精度的圆周率让你算,难道要复制一百多段代码?就算你不辞劳苦复制了100多遍,万一错了,岂不是要修改100多遍。

agx2004 说的很好,平时练习就要注意方法,养成一个好的习惯很重要

楼上厉害啊!一语中的!!