我编写了以下程序,但每次运行时,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;
}
答案 0 :(得分:4)
你的问题就在这里:
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)
while循环将在每次启动时执行该scanf,因此只丢失第一个scanf。
答案 1 :(得分:0)
当你运行while循环while (scanf ("%f", &limit) == 1)
时,它已经运行了scanf ("%f", &limit) == 1
。尝试设置第一个scanf
以输出变量并在while循环中运行变量。