题解 | #牛牛学数列3#
牛牛学数列3
http://www.nowcoder.com/practice/f65c726d081c4160a9356eabf0dc21d9
#include<stdio.h>
int main() {
double val, a, b; //b暂存值
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
a = ((-1) ^ (i - 1)) * (2i - 1); //计算当次分母的值
if (i % 2 != 0) //判断进行加计算或减计算
b += a;
else
b -= a;
val += 1.0 / b; //计算结果
b = 0; //初始化b
}
printf("%.3f", val);
return 0;
}
int main() {
double val, a, b; //b暂存值
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
a = ((-1) ^ (i - 1)) * (2i - 1); //计算当次分母的值
if (i % 2 != 0) //判断进行加计算或减计算
b += a;
else
b -= a;
val += 1.0 / b; //计算结果
b = 0; //初始化b
}
printf("%.3f", val);
return 0;
}