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
- 1.5 50
- Sample Output
- 1.0000
- 0.0707
公式已经给出, 按照公式做就好, 注意分阶段累积, 不要一次性去求, 会炸.(我也不知道为什么会这么说, 隐喻记得 C 做这道题的时候出过问题)
- import java.util.*;
- public class Main {
- public static void main(String[] args) {
- Scanner cin = new Scanner(System.in);
- int n,i,t;
- double x,m,cos,q;
- while(cin.hasNextLine())
- {
- t = -1;
- x = cin.nextDouble();
- n = cin.nextInt();
- cos = 1.0;
- m = 1.0;
- q = 1.0;
- for(i=1;i<=n;i++)
- {
- q *= x*x;
- m *= (2*i)*(2*i-1);
- cos += t * q / m;
- t = -t;
- }
- System.out.printf("%.4f\n",cos);
- }
- cin.close();
- }
- }
来源: http://www.bubuko.com/infodetail-2783382.html