C语言小白求助:用π/4≈1-1/3+1/5-1/7+。。。。公式求π的近似值,直到某一项的绝对值小于1e-6为止

一定要用for语句 我自己弄的一个,乱七八糟的,希望有那位大神赏脸给指正下#include <stdio.h>
#include <math.h>
int main()
{
int s;
double t,n,pi;
s=1,t=1,n=1.0,pi=0;
for(t=1;fabs(t)>=1e-6;n=n+2)
{
pi=pi+t;
s=-s;
t=-s/n;
}
pi=pi*4;
printf("%.6f\n",pi);
return 0;
}

用For语句没有问题。但应该把 pi=pi+t 放到后面,应为执行完for下面的大括号才执行 这句 n=n+2
严格按照你列出来的等式,每执行一次for循环体进行一次算术运算,改成下面这样就可以了
#include <stdio.h>
#include <math.h>
int main()
{
int s;
double t,n,pi;
s=-1,t=1,n=1.0,pi=0;
for(t=1;fabs(t)>=1e-6;n=n+2)
{
s=-s;
t=s/n;
pi=pi+t;
}
pi=pi*4;
printf("%.6f\n",pi);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-01
这道题不要用for语句作,因为循环次数不确定
#include <math.h>
main()
{
int s;
float n,t,pi;
t=1;pi=0;n=1.0;s=1;
while((fabs(t))>1e-6)
{pi=pi+t;
n=n+2;
s=-s;
t=s/n;
}
pi=pi*4;
printf("pi=%10.6f\n",pi);
}本回答被网友采纳
第2个回答  2010-12-01
t=-s/n;这句应该改成 t=s/n;
第3个回答  2010-12-01
确实有点乱 不过你的循环体已经错了!
for(t=1;fabs(t)>1e-6;n++)
{
pi+=t;
s=-s;
t=s/(n+2);
}
第4个回答  2010-12-01
#include<stdio.h>
#include <math.h>
int main()
{
int n;
double s,pi,m;
n=1;s=1.0;pi=0.0;m=1.0;
for(n=1;fabs(m)>=1e-6;n=n+2)
{
m=s/n;
s=-s;
pi+=m;
}
pi=4*pi;
printf("%.6f\n",pi);
return 0;
}
相似回答