C语言习题:计算1/1-1/2+1/3-1/4+1/5 ⋯⋯ + 1/99 - 1/100 的值
思路一:用math.h自带的乘方pow(double a,double b)来实现
#include <stdio.h>
#include<math.h>
int main() {
// insert code here...
double sum = 0.0;
int i = 0;
for (i = 1; i < 101; i++) {
sum += pow(-1, i+1)/i;
}
printf("结果为:%lf\n",sum);
}
思路二: 不使用自带函数的算法:
#include <stdio.h>
int main() {
// insert code here...
double sum = 0.0;
double i = 0;
for (i = 1; i < 101; i += 2) {
sum += 1/i;
}
for (i = 2; i < 102; i += 2) {
sum -= 1/i;
}
printf("结果为:%lf\n",sum);
}
运行结果: