如何使用 while 循环在 c 中评估 pi

how to evaluate pi in c using while loop

我正在尝试用 c 编写代码,以使用 while 循环来近似 pi 的值。我知道使用 for 循环这样做要容易得多,但我正在尝试使用 while 来这样做。 我使用的公式在下面的 link 中: https://www.paulbui.net/wl/Taylor_Series_Pi_and_e 我写的代码是这样的:

#include <stdio.h>
#include <math.h>
int main(){
   long n=10;
   while(n>0){
      double a=0;
      a+=((pow(-1,n))/((2*n)+1));
      n=n-1;
      printf("%ld",4*a);
   }
return 0;
}

我使用 long 和 double 类型的原因是我想精确地进行近似,但首先我应该为这个问题做 st。 提前致谢。

您必须在循环之前移动 a 初始化并设置停止条件 - 例如,计算当前被加数。同样值得在不使用 pow:

的情况下逐步计算符号
double a=0;
double eps= 1.0e-6; //note this series has rather slow convergence
n = 0;
double tx = 1.0;
double t = 1.0;
while(abs(tx)>eps){
   tx = t / (2*n+1)); 
   a+= tx;
   printf("%f",4*a);
   n++;
   t = - t; 
} 

发布的代码没有完全编译!

gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled.c" -o "untitled.o" 

untitled.c: In function ‘main’:
untitled.c:7:19: warning: conversion from ‘long int’ to ‘double’ may change value [-Wconversion]
7 |       a+=((pow(-1,n))/((2*n)+1));
  |                   ^

untitled.c:7:22: warning: conversion from ‘long int’ to ‘double’ may change value [-Wconversion]
7 |       a+=((pow(-1,n))/((2*n)+1));
  |                      ^

untitled.c:9:17: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘double’ [-Wformat=]
9 |       printf("%ld",4*a);
  |               ~~^  ~~~
  |                 |   |
  |                 |   double
  |                 long int
  |               %f

编译成功。

注意:当有警告时,修复那些警告。此外,当出现警告时,编译器会输出最佳猜测,这不一定是您想要的。