Ask your own question, for FREE!
Computer Science 13 Online
OpenStudy (anonymous):

Need help with Pi Approximation on Java Write a Java program which computes PI from the infinite series – Ask the user how many decimal places you should compute PI to and display the number of terms that it takes to compute PI to that many places and the approximation computed. This formula can be used to determine when your approximation is close enough. Math.abs(Math.PI - approx) < (0.5 * Math.pow(0.1, decimalPlaces))

OpenStudy (anonymous):

import java.util.Scanner; public class PiApproximation { public static void main(String[] args) { int decimalPlaces; int terms = 1; double approx = 0.0; int denominator = 1; // Scanner object to read input. Scanner keyboard = new Scanner(System.in); // Ask user for decimal places to // compute PI to. System.out.print("How many digits would you" + " to compute PI to? "); decimalPlaces = keyboard.nextInt(); do { if (terms % 2 == 0) { approx = approx - (4 / denominator); } if (terms % 2 == 1) { approx = approx + (4 / denominator); } else { approx = approx + (4 / denominator); } denominator = denominator + 2; terms++; } while (Math.abs(Math.PI - approx) < (0.5 * Math.pow(0.1, decimalPlaces))); System.out.print("It took " + terms + " to approximate PI as " + approx); } }

OpenStudy (anonymous):

^This is my code, the loop is the only problem I am having with the program.

OpenStudy (e.mccormick):

Did you try any test output to see if it is looping or where it gets stuck? To watch values as it goes through the loop?

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!