Note that there are some explanatory texts on larger screens.

plurals
  1. POMath line only running once in a loop
    primarykey
    data
    text
    <p>this is my first interaction with this site, I have heard good things and I hope I can find the answer that I am looking for. I am learning Java and using the Eclipse IDE in a computer science class at my high school and I came across a problem that neither my teacher or I can solve. Here are the instructions.</p> <blockquote> <p>"The German Mathematician GottfriedLeibniz developed the follow method to approximate the value of π.</p> <p>π/4 = 1 - 1/3 + 1/5 - 1/7 + ...</p> <p>Write a program that allows the user to specify the number if iterations used in this approximation and displays the resulting value."</p> </blockquote> <p>Now the code.</p> <pre><code>import java.util.Scanner; public class GottfriedLeibnizPi { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter how many iterations you want to go to: "); int iterations = reader.nextInt(); double pi = 0; if (iterations &gt;= 0) { for (int count = 0; count &lt;= iterations - 1; count++) { System.out.println("pi: " + pi + " count: " + count); //debug statement to show pi and count before running the code if (count % 2 == 0) { pi = pi + (1 / (1 + (2 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n) } else { pi = pi - (1 / (1 + (2 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n) } System.out.println("pi: " + pi + " count: " + count + "\n"); //debug statement to show pi and count after running the code } pi = pi * 4; //obtains the true value of pi System.out.println("The value of pi after " + iterations + " iterations is " + pi); } else { System.out.println("Please enter a non-negative number"); } } } </code></pre> <p>Here is the output with the the debugging statements if I enter five at the prompt.</p> <pre> Enter how many iterations you want to go to: 5 pi: 0.0 count: 0 pi: 1.0 count: 0 pi: 1.0 count: 1 pi: 1.0 count: 1 pi: 1.0 count: 2 pi: 1.0 count: 2 pi: 1.0 count: 3 pi: 1.0 count: 3 pi: 1.0 count: 4 pi: 1.0 count: 4 </pre> <p>The value of pi after 5 iterations is 4.0</p> <p>My math says that answer should be 3.3396... but the math in my loop does not appear to run more than once. I have not found anything on here that is close to my problem, does anyone know what is wrong?</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