我正在为我的 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/150
提交
取消