JAVA HELP . . QUESTION: . Write a Java console application that approximates PI.
ID: 3863471 • Letter: J
Question
JAVA HELP
.
.
QUESTION:
.
Write a Java console application that approximates PI. Use a validation loop to prompt and get from the user the number of terms to approximate PI to that is at least 1. Use the following Leibniz formula:
--PI approximation = 4 * (1/1 – 1/3 + 1/5 – 1/7 + 1/9 – 1/11 + …)
.
So an approximation to four terms would be:
-- PI approximation = 4 * (1/1 – 1/3 + 1/5 – 1/7)
.
Format the approximation to ten decimal places. Continue to prompt the user for the number of terms until they enter -22. Use number of terms 1,000 for the last input.
Explanation / Answer
public class PIApproximation {
public static void main(String[] args) {
int term =0;
Scanner sc = new Scanner(System.in);
while(term != -22){
System.out.println("Enter Number of Term [-22 for Exit] :");
if(term != -22){
term = sc.nextInt();
System.out.println("PI Approximation : "+getApproximation(term));
}
}
sc.close();
}
public static double getApproximation(int term){
double sign = 1.0d;
double approximation = 0.0d;
int i =1;
while(term>0){
approximation += sign/(double)i;
sign *= -1.0d;
i +=2;
term--;
}
return 4.0d*approximation;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.