gpt4 book ai didi

C++ Pi 估计程序无法正常工作

转载 作者:行者123 更新时间:2023-11-30 00:51:14 26 4
gpt4 key购买 nike

我目前正在编写一个程序,使用此处所示的三个不同公式来估算 Pi 值:http://i.imgur.com/LkSdzXm.png .

到目前为止,这是我的程序:

#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double leibniz = 0.0; // pi value calculated from Leibniz
double counter = 0.0; // starting value
double eulerall = 0.0; // pi value calculated from Euler (all integers)
double eulerodd = 0.0; // value calculated from Euler (odds)

int terms;
bool negatives = false;

cin >> terms;
cout << fixed << setprecision(12); // set digits after decimal to 12 \

while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++;
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++;
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++;

cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}

if (terms < 0){
if(!negatives)
negatives=true;
cout << "There were " << negatives << " negative values read" << endl;
}
return 0;
}

我使用的示例输入文件是:1个6个-5100-10000000

这个输入文件的示例输出是:

1 4.000000000000 2.449489742783 3.174802103936
6 2.976046176046 2.991376494748 3.141291949057
100 3.131592903559 3.132076531809 3.141592586052

当我运行我的程序时,我得到的输出是:

1 4.000000000000 1.224744871392 1.131370849898.

所以你可以看到我的第一个问题是我的方程式的第二个和第三个是错误的,我无法弄清楚为什么。我的第二个问题是程序只读取第一个输入值并停在那里。我希望你们能帮我解决这个问题。非常感谢您的帮助。

最佳答案

你有三个问题:

首先,您没有正确实现欧拉公式。

π2/6 = 1/12 + 1/22 + 1/32 + ...

eulerall = sqrt(6/pow(counter+1,2)) + eulerall;

总和的平方根不是平方根的总和。

π3/32 = 1/13 + 1/33 + 1/53 + ...

eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;

这是……错误的。

其次,您在循环中递增 counter 三次,而不是一次:

while(terms > counter){
...
counter++;
...
counter++;
...
counter++;
...
}

第三,也是最基本的,您没有遵循软件开发的基本规则:从小而简单开始,一次尽可能少地增加复杂性,每一步都进行测试,永远不要添加到不起作用的代码。

关于C++ Pi 估计程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22638839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com