在Java中计算特定数量的术语的Pi?
我被分配了以下任务,但我的代码不起作用。问题是: 使用while或do-while循环,编写一个程序,使用以下等式计算PI:PI=3+4/(2*3*4)-4/(4*5*6)+4/(6*7*8)-4/(8*9*10)+。。。允许用户指定计算中使用的术语数量(显示5个术语)。每次在循环中,PI的估计值只应增加一个额外的项 这是我目前掌握的代码: 导入java.util.Scanner; 导入javax.swing.JOptionPane; 导入java.lang.Math在Java中计算特定数量的术语的Pi?,java,math,pi,Java,Math,Pi,我被分配了以下任务,但我的代码不起作用。问题是: 使用while或do-while循环,编写一个程序,使用以下等式计算PI:PI=3+4/(2*3*4)-4/(4*5*6)+4/(6*7*8)-4/(8*9*10)+。。。允许用户指定计算中使用的术语数量(显示5个术语)。每次在循环中,PI的估计值只应增加一个额外的项 这是我目前掌握的代码: 导入java.util.Scanner; 导入javax.swing.JOptionPane; 导入java.lang.Math public class
public class LabFriday25 {
public static void main(String[] args) {
String termInput = JOptionPane.showInputDialog(null, "How many terms of
PI would you like?");
Scanner termScan = new Scanner (termInput);
double termNum = termScan.nextDouble();
double pi = 3;
int count = 0;
double firstMul = 2;
double secMul = 3;
double thirdMul = 4;
double totalMul = 0;
while (count<= termNum)
{
if (termNum==1)
{
pi = 3.0;
}
else if (count%2==0)
{
totalMul= (4/(firstMul*secMul*thirdMul));
}
else
{
totalMul = -(4/((firstMul+2)*(secMul+2)*(thirdMul+2)));
}
pi = pi + (totalMul);
firstMul = firstMul + 2;
secMul = secMul + 2;
thirdMul = thirdMul + 2;
//totalMul = (-1)*totalMul;
count++;
}
JOptionPane.showMessageDialog(null, "The value of pi in " + termNum + " terms is : " + pi);
}
公共类LabFriday25{
公共静态void main(字符串[]args){
String termInput=JOptionPane.showInputDialog(null,“输入的术语有多少?”
你想要什么?);
扫描仪终端扫描=新扫描仪(终端输出);
double termNum=termScan.nextDouble();
双pi=3;
整数计数=0;
双第一MUL=2;
双secMul=3;
双三分之一毫米=4;
双总MUL=0;
while(countwhile
语句末尾的分号独立计算,导致循环体无条件执行,因此结果始终相同
while (count > 0 && count <= termNum);
^
while(count>0&&count我删除了分号,但现在代码返回用户输入的任何数量的术语的值3.0。有什么想法吗?是的,第一次迭代后,您的循环被炸开了-只需检查数字是否小于上限数字答案现在正在更改,这是一件好事。我的问题是它没有返回输入正确的值。它们更接近正确,但仍然不完全正确。根据输入方程返回的结果是正确的,因此该方程是一个非常松散的近似值PI
,也就是说,这与使用该方程得到的结果一样准确。没有任何东西可以确保序列中的项数与Pi的正确位数相同。我看到这不是一个好的实现。请尝试以下操作:
while (count <= termNum) {