gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:52:31 26 4
gpt4 key购买 nike

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

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

最佳答案

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

循环中的循环将迭代 x*y 次。外层循环的每一步,内层循环都会从头到尾运行。

您需要一个循环来检查这两个条件:

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

但是,因为您想首先执行操作,然后检查条件,所以 do..while 循环更适合这里。您还可以随时中断跳出一个循环,或继续完成当前运行并移至下一个:

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

关于c - 初学者 C - 尝试在数组填满时终止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14406134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com