有两种方法:1.计算出1+1/3+1/5+1/7+…+1/99和1/2+1/4+1/6+1/8+…+1/100的值再让前者减去后者;2.利用for循环改变int flag的符号来计算。
方法1代码:
#include<stdio.h>
int main()
{
int i = 0;
double sum1 = 0, sum2 = 0, sum = 0;
for (i = 1; i <= 100; i += 2)
sum1 += 1.0 / i;
for (i = 2; i <= 100; i += 2)
sum2 += 1.0 / i;
sum = sum1 - sum2;
printf("%lf\n", sum);
}
方法2代码:
#include<stdio.h>
int main()
{
int i = 0;
double sum = 0;
int flag = 1;//flag初始值为正
for (i = 1; i <= 100; i++)
{
sum += flag * 1.0 / i;
flag = -flag;//每次i自加后符号都会变
}
printf("%lf\n", sum);
}