我正在写这个来获取学生信息(最后3个学期的全名,id和gpa,所以我使用了结构和一个for循环来插入信息,但是在第一次学习之后for循环(这意味着在学生2)我的第一个和第二个输入一起显示在屏幕上。我怎么能以简单易懂的方式来防止这种情况发生?(PS:我已经试图把getchar();放在for循环的结束,它的工作,但是,我不应该使用它,因为我们还没有在课堂上所学到)C编程数据输入错误
C程序的一部分在我的错误发生:
#include <stdio.h>
struct Student {
char name[30];
int id;
float gpa[3];
};
float averageGPA (struct Student []);
int main()
{
int i;
float average;
struct Student studentlist[10];
i=0;
for (i; i<10; i++)
{
printf("\nEnter the Student %d full name: ", i+1);
fgets(studentlist[i].name, 30, stdin);
printf("Enter the Student %d ID: ", i+1);
scanf("\n %d", &studentlist[i].id);
printf("Enter the Student %d GPA for the 1st trimester: ", i+1);
scanf("%f", &studentlist[i].gpa[0]);
printf("Enter the Student %d GPA for the 2nd trimester: ", i+1);
scanf("%f", &studentlist[i].gpa[1]);
printf("Enter the Student %d GPA for the 3rd trimester: ", i+1);
scanf("%f", &studentlist[i].gpa[2]);
}
average = averageGPA(studentlist);
printf("\n\nThe average GPA is %.2f", average);
return 0;
}
float averageGPA (struct Student studentlist[])
{
int i;
float total = 0.0, average = 0.0;
for (i=0; i<10; i++)
{
total = studentlist[i].gpa[0] + studentlist[i].gpa[1] + studentlist[i].gpa[2];
}
average = total/30 ;
return average;
}
计算机输出:
Enter the Student 1 full name: mm
Enter the Student 1 ID: 12
Enter the Student 1 GPA for the 1st trimester: 3
Enter the Student 1 GPA for the 2nd trimester: 4
Enter the Student 1 GPA for the 3rd trimester: 3
Enter the Student 2 full name: Enter the Student 2 ID: <<<<< Here is the problem!!
请修改您的文章适当的缩影。它似乎在复制/粘贴期间消失了。 – Lundin
为什么不像所有其他输入一样,对_name_字段使用'scanf'? – Vishal