public class LeibnizFormula {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for(int i=0;i<3;i++){
System.out.print("Enter number: ");
int iteration = sc.nextInt();
double pi = 0;
double denominator = 1;
for (int x = 0; x < iteration; x++) {
if (x % 2 == 0) {
pi = pi + (1 / denominator);
} else {
pi = pi - (1 / denominator);
}
denominator = denominator + 2;
}
pi = pi * 4;
System.out.println(pi);
}
}
}
I have to write a program in Java that follows the Gottfried Leibniz rule:
pi = 1 - (1/3) + (1/5) - (1/7) + ......
I have to allow the user to specify the number of iteration and go from there. I must allow the user to have 3 opportunities to enter the number of iterations (without having to exit the program), and use a for loop for it.
For the actual math part, I don't know whether to use for loop or while loop or if statements--this is the hardest part and I'm so confused. I don't understand. I don't get how the iteration can be counted for (from the user) then applied. Please help me!
Thank you!