题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2011
题目大意:给你 m 个数,对于每个数,求前 n 项和,数列:1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + ...
解题思路:
很水,搞一下就出来了
代码:
1 #include<iostream>
2 #include<cmath>
3 #include<iomanip>
4 //#include<algorithm>
5 double s[1000];
6 using namespace std;
7 int main()
8 {
9 int p = 1;
10 double sum = 0;
11 for(int i = 1; i <= 1000; i ++)
12 {
13 s[i] = s[i - 1] + 1 / (pow(-1, i - 1) * (p++));
14 }
15 int x;
16 int m;
17 while(cin >> m)
18 {
19 for(int i = 0; i < m; i ++)
20 {
21 cin >> x;
22 cout << fixed << setprecision(2) << s[x] << endl;
23 }
24 }
25 }
学到一个三目运算符:
1.a>b?a:c>d?c: d 等价于 a>b?a:(c>d?c:d) 从右往左
2. 1 if(a>b) max=a;
2 else max=b;
可用条件表达式写为 max=(a>b)?a:b;