为了好玩,我试图使用众所周知的算法来计算pi: pi / 4 = 1 - (1/3)+(1/5) - (1/7)+(1/9)等.... 然后将结果乘以4得到pi(近似值)。 我花了最后45分钟左右的时间编写并尝试使用此代码。我搞砸了哪里?任何帮助将不胜感激。
//I'm new, which of these are necessary in this program?
#include <iostream>
using namespace std;
#include <string>
#include <math.h>
int main()
{
//1.0 as 1/4 pi is used as part of the algorithm in the for loop
float pi_fourth = 1.0;
//to be used as a counter inside for loop
int i = 5;
//I want the for loop to stop after only a few iterations
for (pi_fourth = 1.000000; i < 20 ; i + 4)
{
//algorithm for determining one-fourth pi
// algorithm is pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9, etc...
(pi_fourth -= 1/i) += (1/(i-2));
}
//now to complete the program, I need to multiply result
// of the for loop to get pi approx.
float real_pi = (pi_fourth * 4);
//final print statement to reveal pi to a few digits
cout << "pi is ABOUT " << endl << real_pi << endl;
return 0;
}
当它运行时,没有错误出现,它只是永远不会到达最终的print语句,这让我相信这是一个无限循环。这是正确的假设吗?如果答案非常简单,我道歉;正如我之前提到的,我是C ++的新手。
答案 0 :(得分:4)
for (pi_fourth = 1.000000; i < 20 ; i + 4)
i
它没有增加。尝试
for (pi_fourth = 1.000000; i < 20 ; i += 4)
答案 1 :(得分:4)
我制作了一个带有评论的程序的固定版本:
#include <iostream>
// Only iostream is needed for cout and endl.
// using namespace std is usually not recommended on global scope
int main()
{
float pi_fourth = 1.0;
int i = 3;
for(; i < 1000; i += 4)
{
// pi_fourth was already initialized. using 1.00000 instead of 1.0 has no effect.
// i += 4 to add to i
// fixed the algorithm, and wrote it in two statements.
// 1.0/i instead of 1/i, otherwise it would be an integer division (because both 1 and i are integers).
pi_fourth -= 1.0/i;
pi_fourth += 1.0/(i + 2);
}
float real_pi = pi_fourth * 4.0;
std::cout << "pi is ABOUT " << std::endl << real_pi << std::endl;
return 0;
}
答案 2 :(得分:3)
这里有一些关于这个问题的想法,与代码中的错误没有多大关系
在符号更改系列中,错误不会超过最后一次删除的术语。因此,典型的方法是询问用户所需的精度,并从该计算中计算出总数为N
的项数。
它应该从最小项到最大项一起求和,这样就可以保持小错误和控制下的错误。所以循环看起来像
for(int i = N; i > 0; i -= 2)
最好在每个循环周期中添加一个术语,在某些地方
double sign = 1.0;
double pi = 0.0;
for(int i = N; i > 0; i -= 2) {
auto term = sign / double(i);
pi += term;
sign = -sign;
}
return fabs(pi); // might be negative value