Reputation: 1
This is the first part of my high school comp sci lab and I was wondering if I could get some input on why it wasn't working and how I can fix it?
"The German mathematician Gottfried Leibniz developed the method below to approximate the value of PI:
Approximation of Pi Part 1: Write a program that allows the user to specify the number of iterations used in this approximation and displays the resulting value. Use a while loop to accomplish this.
Sample output:
How many iterations would you like to do: 1000
pi: 3.140592653839794"
This is the code I currently have. It doesn't run properly and I'm not sure why or how to fix it either. Right now I'm just trying to get my output the sample's output. Thank you!
//define
Scanner scnr = new Scanner(System.in);
double pi = 0.0;
double n = 0.0; //number of the term starting from 0
System.out.println("How many iterations would you like to do: ");
n = scnr.nextInt();
while (n <= n+1) {
pi = (Math.pow(-1,n) * 4.0) / (2.0 * n + 1);
System.out.println("pi: " + pi);
Upvotes: 0
Views: 586
Reputation: 91
this should do it :)
Scanner scnr = new Scanner(System.in);
double pi = 0.0;
System.out.println("How many iterations would you like to do: ");
int n = scnr.nextInt();
int i = 0;
while (i < n) {
pi += (Math.pow(-1,i) * 4.0) / (2.0 * i + 1);
System.out.println("pi: " + pi);
i++;
}
Upvotes: 1