【问题标题】:Calculating Pi to a specific number of terms in Java?在 Java 中将 Pi 计算为特定数量的术语?
【发布时间】: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 循环中删除了条件。答案更接近正确,但仍然不够准确。我该如何纠正这个问题才能给我正确的答案?

【问题讨论】:

标签: java math pi


【解决方案1】:

while 语句末尾的分号被独立评估,导致循环体无条件执行,因此结果始终相同

while (count > 0 && count <= termNum);
                                     ^

此外,循环在第一次迭代后终止。从循环中删除第一个表达式,即

while (count <= termNum) {

【讨论】:

  • 我删除了分号,但现在代码为用户输入的任意数量的术语返回值 3.0。有什么想法吗?
  • 是的,你的循环在第一次迭代后被炸毁 - 只需检查数字是否小于上限数字
  • 答案现在正在改变,这是一件好事。我的问题是它没有返回正确的值。它们更接近于正确,但仍不完全正确。
  • 根据输入方程返回的结果是正确的,因此方程是PI非常松散近似值,即它与使用该方程得到的一样准确
  • 与 Pi 相比,没有什么可以确保系列中的项数与正确的位数相同。
猜你喜欢
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多