我正在寫這個來獲取學生信息(最後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