我正在为我的Java类编写一个简单的pi计算器,作为我们学习基本循环的一部分,似乎一切正常,除了pi的打印值应为3.14时是无穷大...根据迭代次数。我读到这可能与双变量除以0有关,并且给出了一个奇怪的无穷大输出,而不是普通的Java运行时异常?
这是我的代码:
package lab05;
public class Lab05 {
public static void main(String[] args) {
// Variable declarations
double pie = 3;
double savepie = 0;
double term = 0;
double savei = 0;
double sign = 1;
boolean isRangeFound = false;
int i;
// For loop
for (i=0; i <= 1000;) { // Only up to 1000 iterations before loop must end.
term = (sign * 4) / ((2*i) * (2*i+1) * (2*i+2));
pie = pie + term;
sign = (-1 * sign);
if (isRangeFound==false && (pie >=3.14159265 & pie < 3.14159266)) {
savepie = pie;
savei = i;
isRangeFound = true;
}
if (i == 200||i == 500||i == 1000) {
System.out.print("The value of \u03C0 is: ");
System.out.printf("%.10f",pie);
System.out.print(" when i = " + i);
System.out.println(" ");
}
i++;
}
// Final output statement
System.out.println ("The number of iterations to get to 3.14159265 is " + savei + ".");
System.out.printf("\n\u03C0 = %.10f",savepie);
System.out.println(" ");
}
}
这是我在Netbeans中的输出:
The value of π is: Infinity when i = 200
The value of π is: Infinity when i = 500
The value of π is: Infinity when i = 1000
The number of iterations to get to 3.14159265 is 0.0.
π = 0.0000000000
BUILD SUCCESSFUL (total time: 0 seconds)
这是我应遵循的指示的链接,其中包含我尝试遵循T的Visual Logic流程图。谢谢。 https://www.dropbox.com/s/2m26a32afedk9yu/Lab05%20Assignment%281%29.pdf?dl=0
答案 0 :(得分:1)
当i = 1时,您需要开始循环?您拥有的方式是,当i = 0时,term将是无穷大(由于被零除),所以pie也将是无穷大。