0

私は C の初心者です。King 2nd Edition による最新の C プログラミングへのアプローチを使用しています。

第 6 章で行き詰っています。 問題 1: ユーザーが入力した一連の数値の最大値を見つけるプログラムを作成してください。プログラムは、ユーザーに数字を 1 つずつ入力するように求める必要があります。ユーザーが 0 または負の数を入力すると、プログラムは入力された最大の負でない数を表示する必要があります。

これまでのところ、私は持っています:

#include <stdio.h>

int main(void)
{
float a, max, b; 

for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}

printf("Largest non negative number: %f", max);

return 0;
}

質問の最後の部分、つまりループのユーザー入力の最後でどの負でない数が最大であるかを確認する方法がわかりません。

max = a > a ???

ご協力いただきありがとうございます!

4

2 に答える 2

4

したがって、次のように、ループの各反復で a がそれより大きい場合に max を更新します。

#include <stdio.h>

int main(void)
{
    float max = 0, a;

    do{
        printf("Enter number:");

        /* the space in front of the %f causes scanf to skip
         * any whitespace. We check the return value to see
         * whether something was *actually* read before we
         * continue.
         */

        if(scanf(" %f", &a) == 1) {
            if(a > max){
                max = a;
            }
        }

        /* We could have combined the two if's above like this */
        /* if((scanf(" %f", &a) == 1) && (a > max)) {
         *     max = a;
         * }
         */
    }
    while(a > 0);

   printf("Largest non negative number: %f", max);

   return 0;
}

次に、最後に max を出力するだけです。do while ループは、少なくとも 1 回実行する必要があるため、ここではより適切な選択です。

于 2013-05-23T17:08:08.740 に答える