我正在嘗試在 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 。提前致謝。
uj5u.com熱心網友回復:
您必須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;
}
uj5u.com熱心網友回復:
發布的代碼不能完全編譯!
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://www.uj5u.com/houduan/354727.html
