Question #57821

Write a program that asks the user to input an integer, x, and calculates and prints cos(x) using the above equation series accurate to 10 terms. The final answer should be printed with 5 digits of accuracy after the decimal place.

Expert's answer

public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double x = (double) scanner.nextInt();
double res = 0;
for (int i = 0; i < 10; i++) {
double factorial = 1;
for (int j = 1; j <= 2 * i; j++) {
factorial *= j;
}
res += (i % 2 == 0 ? 1.0 : -1.0) / factorial * Math.pow(x, 2 * i);
}

System.out.println(String.format("%.5f", res));
}
}
LATEST TUTORIALS
APPROVED BY CLIENTS