欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c语言:求多项式1-1/2+1/3-1/4+...+1/99-1/100的值,3种循环实现

程序员文章站 2022-05-23 08:22:10
方法一:for循环实现 程序: #include int main() { double i = 0, t = 0,sum = 0,si...
方法一:for循环实现
程序:
#include<stdio.h>
int main()
{
double i = 0, t = 0,sum = 0,sign = -1;
for (i = 1; i <= 100; i++)
{
sign = -sign;
t =sign/ i;
sum = sum + t;
}
printf("sum=%lf\n",sum);
return 0;
}
方法二:while循环实现
程序:
#include<stdio.h>
int main()
{
double i = 1, t = 0,sum = 0,sign = -1;
while (i <= 100)
{
sign = -sign;
t =sign/ i;
sum = sum + t;
i++;
}
printf("sum=%lf\n",sum);
return 0;
}
方法三:do...while循环实现
#include<stdio.h>
int main()
{
double i = 1, t = 0,sum = 0,sign = -1;
do
{
sign = -sign;
t =sign/ i;
sum = sum + t;
i++;
}
while (i <= 100);
printf("sum=%lf\n",sum);
return 0;
}
结果:
sum=0.688172
请按任意键继续. . .