java中输出PI,使用Java中的Leibniz系列编写程序来估计PI(π)

博主正在尝试编写一个Java程序,根据Leibniz公式估算π,但遇到了无限循环和计数错误的问题。在代码中,外层循环用于递增变量i,内层循环计算系列。尽管代码在硬编码数值时有效,但在动态增加count值时出现问题,导致输出不正确。博主寻求关于如何修正计数问题的建议和指导,而不是直接的解决方案。
摘要由CSDN通过智能技术生成

我在网上看了几个小时试图看看我是否能找到解决方案,而我找到了许多解决方案,我的教授的指示如下:

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”的值进行硬编码时程序是有效的,而不是在增加它时.我知道我听起来很乏味但我真的很想知道出了什么问题以及为什么会出错.

我意识到简单地在这里发布解决方案并不是一个好的形式所以我不是要求它,我只需要一些伪代码或指针.我已经做了很长一段时间了.谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值