4

我已经编写了以下程序,但是每次我运行它时,for 循环都不起作用,直到我输入另一个数字。然后使用输入的第二个数字运行 for 循环。为什么会这样?似乎没有人遇到这个问题......这是程序:

#include <stdio.h>
#include <math.h>

int main(void)
{

float limit;
float count;
float series1, series2;

printf("Enter a limit for the series ");
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1) 
{
    for (series1 = 1, count = 2; count <= limit; count++)
            series1 += 1.0/count;
            printf ("\nThe sum of the first infinite series is %.4f", series1);
    for (series2 = 1, count = 2; count <= limit; count++)
            series2 += (1.0/count) * pow ((-1),(count - 1));
            printf ("\nThe sum of the second infinite series is %.4f", series2);

        printf("\n\nEnter a limit for the series (q to quit) ");
        scanf ("%f", &limit);
}
return 0;

}
4

2 回答 2

4

你的问题就在这里:

scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)

while 循环每次启动时都会执行该 scanf,因此只需丢失第一个 scanf。

于 2012-11-11T19:42:05.597 回答
0

当您运行 while 循环while (scanf ("%f", &limit) == 1)时,它会scanf ("%f", &limit) == 1在您已经运行它之后再次运行。尝试将第一个设置scanf为输出变量并在 while 循环中运行该变量。

于 2012-11-11T19:41:47.850 回答