我在网上看了几个小时试图看看我是否能找到解决方案,而我找到了许多解决方案,我的教授的指示如下:
Write a program to estimate PI (π) using the following series. This problem is also described in the text as problem 5.25 at the end of chapter 5. If you are unfamiliar with series, problem 5.24 is a single pass through a series and the solution is posted in the Homework 3 course module.
π=4*(1-1/3+1/5-1/7+1/9-1/11+⋯〖-1〗^(i+1)/(2i-1))
Obviously, there is no user input for this problem so a modified worksheet is provided. You will to write a program that computes PI using i values of 10,000 to 100,000 in increments of 10000. Your output should look like: (Hint: Placing “/t” in the System.out.println between the values of i and PI will give you columns. This is the tab character).
i________PI
10000 ____ 3.xxxxx
20000 ____ 3.xxxx
30000 ____ 3.xxxx
You will need multiple loops to do this. The outer loop will increment i. The inner loop will compute the series from 1 to i. You may use any of the three types of loops, for, while, or do-while to do this.
现在我很清楚除了这个之外还有很多方法可以更好地找到pi,但是这个任务的重点不是要有效地找到Pi而是用循环练习.但是我尝试了很多方法,所有方法都返回无限循环,输出不正确,或者它们只是不编译.
编辑:感谢Martijn Courteaux,我在代码方面取得了很大的进步.但是我仍然无法使计数正确增加.有什么建议?
我最近的尝试如下.
公共课LeibnizFormula {
public static void main(String [] args){
System.out.println("i/t Pi");
int count = 10000;
double pi = 0;
double denominator = 1;
while(count < 100000){
for (int x = 0; x < count; x++) {
if (x % 2 == 0) {
pi = pi + (1 / denominator);
}
else {
pi = pi - (1 / denominator);
}
denominator = denominator + 2;
}
pi = pi * 4;
System.out.println(pi);
count = count + 10000;
System.out.println(count);
}
}
}
现在的结果是:
i/t Pi
3.1414926535900345
20000
12.566037281026608
30000
50.264165790773355
40000
201.05666982975973
50000
804.2266826523694
60000
3216.9067325142446
70000
12867.626931247545
80000
51470.50772578291
90000
205882.03090368543
100000
我真的不明白为什么当我对“count”的值进行硬编码时程序是有效的,而不是在增加它时.我知道我听起来很乏味但我真的很想知道出了什么问题以及为什么会出错.
我意识到简单地在这里发布解决方案并不是一个好的形式所以我不是要求它,我只需要一些伪代码或指针.我已经做了很长一段时间了.谢谢