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
Source
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.0000");
while(input.hasNext()) {
double x,s;
int n,i,j;
x = input.nextDouble();
n = input.nextInt();
s = 1;
for(i = 1;i <= n;i++) {
if(i % 2 != 0) {
double a = 1;
for(j = 1;j <= 2*i;j++) {
a = a * j;
}
double b = 1;
for(j = 1;j <= i*2;j++) {
b = x*b;
}
s = s - (b*1.0/a);
}
else {
double a = 1;
for(j = 1;j <= 2*i;j++) { //求n的阶乘
a = a * j;
}
double b = 1;
for(j = 1;j <= i*2;j++) { //求x的2*i次方
b = x*b;
}
s = s + (b*1.0/a);
}
}
System.out.println(df.format(s));
}
input.close();
}
}