方法1.pow函数型
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i = 0;
double sum = 0;
for (i = 1; i <= 100; i++)
{
sum += (pow(-1, i+1) * 1 / i); // pow(x,y),计算x的y次方,x、y及函数值均为double型
}
printf("sum=%lf\n", sum); //打印浮点型
system("pause");
return 0;
}
方法2.数学型
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
double sum= 0.0;
for (i = 1; i <= 100; i++)
{
if (i % 2 != 0)
{
sum += (1.0 / i); //左右两边类型应该保持一致
}
if (i % 2 == 0)
{
sum -= (1.0 / i);
}
}
printf("sum=%lf\n", sum);
system("pause");
return 0;
}
方法3.1.for循环
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 1;
float sign = 1.0; sum = 0.0;
for (i = 1; i <= 100; i++)
{
sum += sign / i;
sign = -sign;
}
printf("sum=%f\n", sum);
system("pause");
return 0;
}
方法3.2.while循环
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 1;
float sum = 0.0, sign = -1;
while (i <= 100)
{
sign = -sign;
sum += sign/i;
i++;
}
printf("sum=%lf\n", sum);
system("pause");
return 0;
}
方法3.3.do...while循环
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 1;
float sum = 0.0, sign = -1;
do
{
sign = -sign;
sum += sign / i;
i++;
}
while (i <= 100);
printf("sum=%lf\n", sum);
system("pause");
return 0;
}