【发布时间】:2013-10-28 14:15:09
【问题描述】:
我被分配了以下任务,但我的代码不起作用。问题是:
使用 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 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);
}
}
我不明白为什么代码不会为 Pi 的 3 个或更多术语返回正确的值,它每次都给出相同的值。
编辑:我从 while 语句的末尾删除了分号,现在代码为用户输入的任意数量的术语返回值 3.0。我哪里错了?
EDIT2:从 while 循环中删除了条件。答案更接近正确,但仍然不够准确。我该如何纠正这个问题才能给我正确的答案?
【问题讨论】:
-
我可以看到这不是一个好的实现。试试这个:math.hmc.edu/funfacts/ffiles/30001.1-3.shtml