初学者C - 尝试在填充数组时终止循环

时间:2013-01-18 19:24:25

标签: c arrays loops while-loop

我有一个家庭作业问题,我必须记录成绩,将它们放在一个数组中,然后给出平均值。该程序应该要求输入,直到给出负数作为等级或数组被填充。到目前为止,我能够使程序循环,直到我给出一个负数,并计算正确的平均值。我无法弄清楚的是如何在数组填充时终止循环。我的代码:

#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 */

3 个答案:

答案 0 :(得分:1)

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

循环中的循环将迭代x * y次。对于外循环的每个步骤,内部循环将从开始到结束。

你需要一个循环检查两个条件:

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

但是,因为你想先做事情然后检查条件,do..while循环更适合这里。您也可以随时break一个循环或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*/

答案 1 :(得分:0)

检查是否

MAX_GRADES == counter 

并打破循环。但无论如何都要这样做......你根本不需要改变你的代码。

答案 2 :(得分:0)

你可以摆脱内部循环,只需将外循环上的while条件更改为:

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