我同时使用了莱布尼茨和瓦利斯公式来估算π但输出数字错误,我不知道我哪里出错了


#include <cmath> \not sure if I need cmath
#include <iostream>
using namespace std;

这个while循环用于循环"输入要近似的项数。

while (a != 0)
{

这是莱布尼兹公式:

double c = 0.00, d = 0.00;
for (int i = 1; i <= a)
{
if (i % 2 != 0)
{

d = 1 / (1 + 2 * (i - 1));
}
else
{
d = -1 / (1 + 2 * (i - 1));
}
c = c + d;
i = i + 1
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(5);
cout << "The approximation for Leibniz's Formula is " << c << " 
using "<< a <<" terms." << endl;

这是瓦利斯公式:

double e = 1.00;
for (int u = 0; u<a; u++)
{
e = e * (2 * a / (2 * a - 1))*(2 * a / (2 * a + 1));
}
cout << "The approximation for Wallis' Formula is " << e << " using 
"<< a <<" terms." << endl;
cout << endl;
cout << "Enter the number of terms to approximate (or zero to 
quit):" << endl;
cin >> a;
}

对于a=1,我在第一个公式输出中得到1.0000,在第二个公式输出中得到0.00000

类似的行

d = 1 / (1 + 2 * (i - 1));

将使用整数运算来计算结果,然后将int结果转换为double

将其更改为

d = 1.0 / (1 + 2 * (i - 1));

甚至

d = 1.0 / (1.0 + 2.0 * (i - 1.0));

这段代码中有很多错误。首先,c++中的注释使用//,而不是\

#include <cmath> //not sure if I need cmath

对于语句,在中必须有两个分号,即使不需要循环表达式

for (int i = 1; i <= a;)

对于每一个大于1的id将求值为0。当您显然想要浮点除法时,您使用的是整数除法。你必须像这样告诉编译器。

d = 1.0 / (1 + 2 * (i - 1));

当除法运算符的左参数为double时,编译器将知道您要执行浮点除法。如果在您的代码中是int,则将执行整数除法并将结果转换为double

此外,在Wallis公式中,您将a放错了位置,表示u,并且u参数应该从1开始,而不是0。此外,整数除法问题在这里仍然存在。

double e = 1.00;
for (int u = 1; u<a; u++)
{
e = e * (2.0 * u / (2.0 * u - 1))*(2.0 * u / (2.0 * u + 1));
}

如果全部修复,程序将开始输出有效的结果。

最新更新