C语言中的“ For”循环不断循环

时间:2018-12-02 22:46:28

标签: c infinite-loop

我知道之前已经有人问过这个问题,但是我一直找不到适合我的情况的答案。

我一直无法结束这个For循环。我敢肯定这很简单,谁能告诉我我在做什么错?

#include <stdio.h>
int main ()
{
  /* variable definition: */
  char StudentName[100];
  float ExamValue, Sum, Avg;
  int students, exams;
  int Total_Students;

    printf("Enter total number of students: \n");
    scanf("%d", &Total_Students);

   // Loop through x students
  for (students = Total_Students; students++;)
  {
     // reset Sum to 0
     Sum =0.0;  
     printf("Enter Student Name \n");
     scanf("%s", StudentName); 

     // Nested Loop for Exams
    for (exams=0; exams < 3; exams++)
    {
        printf ("Enter exam grade: \n");
        scanf("%f", &ExamValue);
        Sum += ExamValue;
    }   
    Avg = Sum/3.0;
    printf( "Average for %s is %f\n",StudentName,Avg);
  }
  return 0;
}

2 个答案:

答案 0 :(得分:2)

在预期将循环x个学生的外循环中,实际上是从x个学生开始,并达到无穷大。您应该从零开始,并以“学生总数”为界。

答案 1 :(得分:-3)

此代码可以解决您的问题。 您应该这样设置条件,准确设置起点,终点

#include <stdio.h>
int main()
{
/* variable definition: */
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
int Total_Students;

printf("Enter total number of students: \n");
scanf_s("%d", &Total_Students);

// Loop through x students
// you should make condition like this, set the start, end point accurately
for ( students = Total_Students; students>0; students--)
{
    // reset Sum to 0
    Sum = 0.0;
    printf("Enter Student Name : \n");
    scanf_s("%s", StudentName,sizeof(StudentName));
    getchar();

    // Nested Loop for Exams
    for (exams = 0; exams < 3; exams++)
    {
        printf("Enter exam grade: \n");
        scanf_s("%f", &ExamValue);
        Sum += ExamValue;
    }
    Avg = Sum / 3.0;
    printf("Average for %s is %f\n", StudentName, Avg);
}
return 0;
}