4

次のプログラムを作成しましたが、実行するたびに、別の数値を入力するまで for ループが機能しません。次に、入力された 2 番目の数値を使用して 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 に答える