######作业中遇到求和问题始终得不出精确值
int i = 1;
int a=1;
int c;
int b;
while (a <= 100)
{
c = 0;
for (b = 1; b <=a; b++)
{
c = c+1;
}
i = -i;
c = c * i;
sum = sum +(1 / c);
a++;
}
printf("%f\n", sum);
把第14行的1改为1.0即可,因为和是小数,把1改为1.0即可让整数运算变为double类型运算,从而可以让结果更准确,修改如下:
#include <stdio.h>
int main(void){
double sum=0;
int i = 1;
int a=1;
int c;
int b;
while (a <= 100)
{
c = 0;
for (b = 1; b <=a; b++)
{
c = c+1;
}
i = -i;
c = c * i;
sum = sum +(1.0 / c); // 把这里的1改为1.0,让整数运算变为double类型运算
a++;
}
printf("%f\n", sum);
}
1 / c 2个int相除的结果是int,会丢弃小数部分。改为1.0 / c
来个简洁的写法
#include <stdio.h>
int main()
{
double c = 1, sum = 0;
for (int i=2;i<=101;i++)
{
sum = sum + (1 / c);
if (c < 0)
c = i;
else
c = -i;
}
printf("%f\n", sum);
}