我正在尝试用c写一段代码,使用while循环来近似pi的值。我知道使用for循环这样做要容易得多,但我正在尝试使用while来做到这一点。我使用的公式在下面的链接中: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。提前谢谢。
发布于 2021-11-08 23:13:10
您必须将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;
}
发布于 2021-11-09 08:15:40
发布的代码不能干净地编译!
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
编译已成功完成。
注意:当出现警告时,修复这些警告。此外,当出现警告时,编译器会输出它的最佳猜测,这不一定是您想要的。
https://stackoverflow.com/questions/69894035
复制