Domanda

I've been given the following assignment and my code isn't working. The question is:

Using a while or a do-while loop, write a program to compute PI using the following equation: PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ... Allow the user to specify the number of terms (5 terms are shown) to use in the computation. Each time around the loop only one extra term should be added to the estimate for PI.

This is the code I have so far: import java.util.Scanner; import javax.swing.JOptionPane; import 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);
    }

}

I can't figure out why the code won't return the right value for 3 or more terms of Pi, it keeps giving the same value every time.

EDIT: I removed the semi-colon from the end of the while statement and now the code is returning the value 3.0 for any number of terms inputted by the user. Where am I going wrong?

EDIT2: Removed condition from while loop. Answers are closer to being correct, but still not accurate enough. How can I correct this to give me the right answer?

È stato utile?

Soluzione

The semi-colon at the end from the while statement is evaluated independently causing the body of the loop to execute unconditionally so the result is always the same

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

In addition the loop is terminating after the first iteration. Remove the first expression from the loop, i.e.

while (count <= termNum) {
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top