【C语言代码】
两种典型实现如下:

#include <stdio.h>
#include <stdlib.h>

int main() {
	float s=0.0;
	for(int i=1;i<=100;i++){
		if(i%2!=0) s=s+1.0/i;
		else s=s-1.0/i;
	}
	printf("%f",s);
	
	return 0;
}

/*
out:
0.688172
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
	float s=0.0;
	double t;
	int i;
	for(i=1; i<=100; i++) {
		t=pow(-1,i-1);
		s=s+t/i;
	}

	printf("%f",s);

	return 0;
}

/*
out:
0.688172
*/


【C语言代码分析】
1.注意语句 float s=0.0; 中使用 0.0 (而不是0)赋值给 float 类型变量。
2.注意语句 s=s+1.0/i; 中除号左边使用1.0,才能保证 1.0/i 的值为 float 类型。
3.注意语句 pow(-1,i-1) 表示“-1 的 i-1 次方”。

更多推荐

编程题:利用C语言编程计算1-1/2+1/3....+1/99-1/100的值