从题目看应先输入项数n(正整数),再用for循环求结果较方便;计数变量从1开始依次增1,奇数取其倒数为正、偶数取其倒数为负求各项之浮点和即可完成。代码如下:
#include "stdio.h"
int main(int argc,char *argv[]){
double s;
int i,n;
printf("Input n(int n>0)...\nn=");
if(scanf("%d",&n)!=1 || n<1){//限制输入的项数n是正整数
printf("Input error, exit...\n");
return 0;
}
for(s=0,i=1;i<=n;s += i&1 ? 1.0/i++ : -1.0/i++);//i从1开始求倒数,奇数时取正,否则取负求浮点和
printf("The result are %g\n",s);//输出结果
return 0;
}
试运行结果如下:
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/472309f790529822265aec78ddca7bcb0a46d424?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)