对于我这种初学者比较容易理解的两种方法
第一种是先计算正数的和,然后计算负数的和,最后加在一起。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
float a, b;
float c = 0 ;
float d = 0;
for (b = 1; b < 100; b = b + 4)//计算正分数的和
{
a = b + 2;
float num = 1 / b + 1 / a;
c = c + num;
}
printf("正数的和:%f\n", c);
for (b = 2; b <= 100; b += 4)//计算负数的和
{
a = b + 2;
float num = - 1 / b - 1 / a;
d = d + num;
}
printf("负数的和:%f\n", d);
float mun = d + c;
printf("总和:%f\n", mun);
return 0;
}
第二种方法是直接计算总和
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
float Add(float x, float y)
{
float z = 0;
z = 1 / x - 1 / y;
return z;
}
int main()
{
float a ;
float b ;
float c = 0;
float s = 0;
for (a = 1; a <= 100; a += 2)
{
b = a + 1;
float sum = Add(a, b);
s = s + sum;
}
printf("%f\n", s);
return 0;
}
|