Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculating Pi to a specific number of terms in Java?
    primarykey
    data
    text
    <p>I've been given the following assignment and my code isn't working. The question is:</p> <p>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.</p> <p>This is the code I have so far: import java.util.Scanner; import javax.swing.JOptionPane; import java.lang.Math;</p> <pre><code>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&lt;= 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); } </code></pre> <p>}</p> <p>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.</p> <p>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?</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload