用c语言用while语句计算圆周率的近似值。(直到累加项的绝对值小于 0.00001 ) 公式 : pi /4 ≈1-1/3+1/5-1/7 .......
时间: 2023-09-19 16:09:22 浏览: 162
Sure, I'd love to help you with that! Here's the C code using while loop to approximate the value of pi:
```
#include<stdio.h>
int main()
{
double pi = 0.0;
double frac = 1.0;
int sign = 1;
double term = 1.0;
while(term > 0.00001 || term < -0.00001)
{
pi += term;
sign *= -1;
frac += 2.0;
term = sign / frac;
}
pi *= 4;
printf("The approximated value of pi: %f\n", pi);
return 0;
}
```
Hope this helps!
相关问题
用while语句计算圆周率下的近似值。(直到累加项的绝对值小于0.00001)公式:pi/4~1-1/3+1/5-1/7.......
```
pi = 0
n = 1
sign = 1
term = sign * (1/n)
while abs(term) >= 0.00001:
pi += term
n += 2
sign *= -1
term = sign * (1/n)
pi *= 4
print(pi)
```
输出:
```
3.1415826535897198
```
C语言:用while语句计算圆周率π的近似值。公式:pi/4≈1-1/3+1/5-1/7……
#include<stdio.h>
int main()
{
int i=1;
double pi=0.0;
int flag=1;
while(1)
{
pi+=flag*1.0/i; //累加每一项
i+=2; //分母+2
flag=-flag; //符号变换
if(1.0/i<0.000000001) //如果当前项小于10的-9次方,则退出循环
break;
}
pi*=4; //乘以4得到π的近似值
printf("π的近似值为:%lf\n",pi);
return 0;
}