我有两个不同的程序,一个是用for循环找到一个有限数的Riemann求和,虽然我最后发现了一些愚蠢的舍入错误,但这个程序似乎工作得很好。第二个程序使用while循环并打印迭代,直到指定的值。第一次弹出值是在M=226,但是当我运行while循环时,它显示在227。我不明白为什么会这样。
int main()
{
int i=1,m=0;
double x=0.0;
printf ("the sum of i/(4i+2)^3 as i goes from one to M, please enter a M\n");
scanf ("%d",&m);
for(i;i<=m;i++)
{
x=x+(i/pow(4*i+2,3));
}
printf("the sum of your series is %.9lf\n", x);
return 0;
}#include <stdio.h>
#include <math.h>
int main()
{
int i=0;
float x=0.0;
while (x<0.011300)
{
x = x+((float)i/pow(4*i+2,3));
i++;
}
printf("%d", i);
return 0;
}任何建议都会很好。
发布于 2015-02-07 11:24:21
如果在循环后的第一个示例中添加printf("after the loop is over, the i is equal to %d\n", i);,则会看到它在末尾等于227,而不是226。
您错误地假设在执行结束时i必须等于226。当循环条件上一次为真(即为真)时,它是 226,然后执行数学计算,然后它增加,从而变成227。在此之后,在下一次迭代中,循环就结束了,因为i <= m不再是真了(此时的i是227 )。
https://stackoverflow.com/questions/28378953
复制相似问题