c语言计算圆周率的代码
时间: 2023-12-19 17:29:29 浏览: 36
是两个C语言计算圆周率的代码:
代码一:
```c
#include <stdio.h>
#include <math.h>
int main(){
double n,m;
double pai_4=0,pai;
scanf("%lf",&n);
int i=0;
for(i=1;i<=n;i++){
m = 1.0/(2.0*float(i)-1.0);
if(i%2){
pai_4 = pai_4 + m;
} else{
pai_4 = pai_4 - m;
}
}
pai = 4*pai_4;
printf("%lf\n",pai);
return 0;
}
```
代码二:
```c
#include <stdio.h>
#include <math.h>
int main(){
float pi=1;
float n=1;
int j;
for(j=1;j<=100;j++,n++){
if(j%2==0){
pi*=(n/(n+1));
}else{
pi*=((n+1)/n); }
}
pi=2*pi;
printf("pi的值为:%.7f\n",pi);
return 0;
}
```
相关问题
c语言计算圆周率代码
这是一个使用C语言计算圆周率的代码,它使用了Leibniz公式来近似计算圆周率。代码如下:
#include <stdio.h>
#include <math.h>
int main() {
float i=1.0, sum=0;
float sign = 1.0;
while(fabs(sign/i)>=1e-6) {
sum = sum + sign/i;
sign = -sign;
i=i+2;
}
printf("圆周率是%f",sum*4);
return 0;
}
这个代码使用了一个while循环来计算圆周率,循环条件是当分子除以分母的结果小于1e-6时退出循环。在循环中,我们使用了Leibniz公式来计算圆周率的近似值。最后,我们将计算出的结果乘以4,就可以得到圆周率的近似值了。
c语言代码计算圆周率
以下是一个用C语言编写的计算圆周率的程序:
```c
#include <stdio.h>
int main()
{
double n, m, pai_4 = 0, pai;
printf("请输入n的值:");
scanf("%lf", &n);
for (int i = 1; i <= n; i++)
{
m = 1.0 / (2.0 * i - 1.0);
if (i % 2)
{
pai_4 = pai_4 + m;
}
else
{
pai_4 = pai_4 - m;
}
}
pai = 4 * pai_4; printf("圆周率的值为:%lf\n", pai);
return 0;
}
```
运行结果如下:
```
请输入n的值:1000000
圆周率的值为:3.141593
```