0

成績を記録し、それらを配列に入れ、平均を出さなければならない宿題の問題があります。プログラムは、成績として負の数が与えられるまで、または配列が満たされるまで、入力を求めることになっています。これまでのところ、負の数を与えるまでプログラムをループさせることができ、正しい平均が計算されます。私が理解できないのは、配列がいっぱいになったときにループを終了する方法です。私のコード:

#include <stdio.h>

/* function main begins program execution */
int main( void )
{  int counter; /* number of grade to be entered next */
   int grade; /* grade value */
   int total; /* sum of grades input by user */
   double average; /* average of grades */

   /* initialization phase */
   total = 0; /* initialize total */
   counter = 0; /* initialize counter */
   grade = 0;  /* initialize grade */

   printf( "Input a negative number when done entering grades.\n" );

   /* processing phase */
   #define MAX_GRADES 20
   int grades [MAX_GRADES];
   while ( counter < MAX_GRADES) {
     while ( grade >= 0 ) { /* loop until negative given */
       printf( "Enter grade: " ); /* prompt for input */
       scanf( "%d", &grade ); /* read grade from user */
       if (grade >= 0) {
     if (grade > 100)
       printf( "Grade is greater than 100. Please input grade again.\n" );
     else {
       grades[counter] = grade;
       total = total + grade; /* add grade to total */
       counter = counter + 1;
     } /* end else */
       } /* end if */
     } /* end while */
   } /* end while */

   /* termination phase */
    average = total /(double) counter; /* integer division */

   printf( "Class average is %f\n", average ); /* display result */
   return 0; /* indicate program ended successfully */
} /* end function main */
4

3 に答える 3

1
while ( counter < MAX_GRADES) {
    while ( grade >= 0 ) {

ループ内のループはx*y回繰り返されます。外側のループの各ステップで、内側のループは最初から最後まで実行されます。

両方の条件をチェックする1つのループが必要です。

while ( counter < MAX_GRADES && grade >= 0) 

ただし、最初に処理を実行してから状態をチェックするため、do..whileここではループの方が適しています。またbreak、いつでも1つのループから抜け出したりcontinue、現在の実行を終了して次のループに移動したりすることもできます。

do{ /* loop */
   printf( "Enter grade: " ); /* prompt for input */
   scanf( "%d", &grade ); /* read grade from user */
   if (grade < 0)
     break;

   if (grade > 100){
     printf( "Grade is greater than 100. Please input grade again.\n" );
     continue;  
   }

   /* all abnormal conditions have been handled */
   /* now we're clear to do the actual job */

   grades[counter] = grade;
   total = total + grade; /* add grade to total */
   counter = counter + 1;

 }while ( counter < MAX_GRADES ) /*until array is full*/
于 2013-01-18T19:30:08.437 に答える
0

確認するだけ

MAX_GRADES == counter 

ループを解除します。しかし、これはとにかく行われます...コードを変更する必要はまったくありません。

于 2013-01-18T19:27:41.430 に答える
0

内側のループを取り除き、外側のループのwhile条件を次のように変更できますか?

while ( counter < MAX_GRADES && grade >= 0 )
于 2013-01-18T19:27:53.850 に答える