【发布时间】:2015-12-26 22:32:49
【问题描述】:
为了好玩,我正在尝试使用众所周知的算法计算 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;
}
当它运行时,没有错误出现,它永远不会到达最终的打印语句,这让我相信这是一个无限循环。这是一个正确的假设吗?如果答案非常简单,我深表歉意;正如我之前提到的,我是 C++ 新手。
【问题讨论】:
-
for (pi_fourth = 1.000000; i < 20 ; i + 4)i + 4 什么都不做,所以你有一个无限循环,因为 i 永远不会改变。 -
Clang: 警告:表达式结果未使用 [-Wunused-value],
i + 4下带有波浪线。 -
从未见过这样的符号
(pi_fourth -= 1/i) += (1/(i-2));,我想知道这是否有效。但是这里不适用整数除法吗? -
@rekire,赋值表达式返回被赋值的事物,因此它是有效的。不过,它可能作为两个语句更具可读性。
-
我从来没有高效地使用过 C++,所以我不是最好的人,但我会写成
pi_fourth -= 1/(i*1.0) + 1/(i-2.0);
标签: c++ runtime-error infinite-loop pi