C循环具有未确定的数字

时间:2016-02-21 09:47:44

标签: c for-loop nested-loops

过去几天我一直难过,试图修改我当前的代码,以便输入不确定数量的学生。

#include <stdio.h>

int main(void)
{
   char StudentName[100];
   float ExamValue, Sum, Avg;
   int students, exams;

   for (students = 0; students < 5; students++)
   {
      Sum = 0.0;
      printf("Enter Student Name \n");
      scanf("%s", StudentName);

      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;
}

就像现在一样,我必须手动输入学生数量。有谁知道如何修改此代码以输入不确定数量的学生?我开始认为不可能做到并保持其余代码的完整性。非常感谢任何帮助,谢谢!

4 个答案:

答案 0 :(得分:4)

您可以执行类似while (stillAdding)而不是for循环的操作,并使用Enter student name or QUIT to stopWould you like to enter a new student [Y/n]提示用户。您相应地修改了stillAdding变量。简而言之,您可以将其留给用户指定何时停止输入更多数据。

答案 1 :(得分:1)

您可以在for之前询问用户数,然后将该数字用作for的上限。像这样:

int students, exams, nr;
printf("Enter Student Number \n");
scanf("%d", &nr);
for (students = 0; students < nr; students++)
{
    //your code
}

答案 2 :(得分:0)

您可以询问用户每个循环是否有更多学生:

#include <stdio.h>

int main(void)
{
    char StudentName[100];
    float ExamValue, Sum, Avg;
    int students, exams;
    char stop;

    for (;;)
    {
        Sum = 0.0;
        printf("Enter Student Name \n");
        scanf(" %s", StudentName);
        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);

        puts("More students?(Y/N)");
        scanf("%*[^yYnN]%c%*[^\n]%*c", &stop); // read one of 'y', 'Y', 'n', 'N', then discard that line, including '\n'.
        if (stop == 'N' || stop == 'n')
            break;
    }
    return 0;
}

答案 3 :(得分:0)

enter image description here

您可以提示用户提供输入数量。一旦用户告诉您将给出多少输入,那么您可以简单地使用for循环来读取那么多输入