大家好,我正在尝试使用以下公式计算pi:
pi = 4·[1 – 1/3 + 1/5 – 1/7 + 1/9 ... +(–1)^ n /(2n +1)]
但是我的输出pi值始终为零,而我错在哪里真的让我感到困惑。这是我的代码:
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int n;
double b = 0;
char c = 'Y';
int s = 1;
while (c == 'Y') {
cout << "Enter the value of the parameter 'n' in the Leibniz formula (or -1 to quit):" << endl;
cin >> n;
if (n != -1) {
c = 'Y';
for (int a = 1; a <= n; a++) {
s = -s;
b += 4 * (s/ (2 * a + 1));
}
cout << "The approximate value of pi using 1 term is:" << b << endl;
}
else {
c = 'N';
}
}
return 0;
}
最佳答案
在C和C ++中,对整数的数学运算都会得出整数,即使结果在常规数学中是小数也是如此。将您的int
更改为float
或double
,我怀疑它会更好。
结果将被截断为整数值并具有整数类型。
因此,例如:2 / 4
生成0
,而5 / 2
将生成2
。
注意如果在浮点值和整数值之间执行运算,则结果为浮点值。所以:
2.0 / 4 == 0.5
关于c++ - 如何在C++中以3位小数精度计算pi?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45025560/