In: Computer Science
Replace <missing code> with your answer. Your code should approximate the value of π (~3.141592653589793). You can approximate pi using the following formula:
π = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + …)
For this problem, let n be the number of terms to add in the series. For example, if n = 5, your code should compute the following: 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9). If n = 3, your code should compute 4 * (1 - 1/3 + 1/5)
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int piApprox = <missing value>;
<missing code>
System.out.println("piApprox = " + piApprox);
}
import java.util.Scanner;
public class CalcPiApprox {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
int n = scanner.nextInt();
// we need to make piApprox
double
// otherwise, values will be
rounded off
double piApprox = 0;
// Initially, set denominator
for term to 1
double denom = 1;
int terms = 0;
while (terms < n) {
// Increment
denom by 2 and term by 1 after calculating one term
piApprox =
piApprox + 1 / denom;
denom +=
2;
terms += 1;
// Check if
term = n, if yes break
// This could be
the case when n is odd
if (terms == n)
{
break;
}
// Increment
denom by 2 and term by 1 after calculating another term
piApprox =
piApprox - 1 / denom;
denom +=
2;
terms +=
1;
}
// Multiply piApprox by 4 and
print the result
piApprox = piApprox * 4;
System.out.println("piApprox = " +
piApprox);
}
}
OUTPUT