C语言实验——余弦
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
输入n的值,计算cos(x)。

Input
输入数据有多行,每行两个数,包括x和n。第一数据为x,第二个数据为n。
Output
输出cos(x)的值,保留4位小数。
Sample Input
0.0 100
Sample Output
1.0000
Hint
递推:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
double x = sc.nextDouble();
double n = sc.nextDouble();
double sum = 0.0, flag = 1.0, s = 1.0;
for(int i = 0; i <= n; i++) {
if(i != 0) {
s = s * (x * x) * 1.0 / ((2 * i)* (2 * i - 1));
}
sum += (s * flag);
flag = -flag;
}
System.out.println(String.format("%.4f", sum));
}
sc.close();
}
}
公式法:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()) { double x = sc.nextDouble(); double n = sc.nextDouble(); double sum = 1; double x1, x2; for(int i = 1; i <= n; i++) { double t = 1; for(int j = 1; j <= 2 * i; j++) { t *= j; } sum += Math.pow(x, 2*i)/(t *Math.pow(-1, i)); } System.out.println(String.format("%.4f", sum)); } sc.close(); } }