[英]Why does my program terminate after the while loop?
下面的程序應該詢問用戶他想要給多少學生評分,然后讓用戶輸入成績並獲得平均分。
#include <stdio.h>
#include <stdlib.h>
struct person {
char Name[100];
int ID;
int Age;
double Score;
};
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
int size;
printf("How many students are you grading?(Not more than 100)-->");
scanf("%d",&size);
struct person *student;
double total=0,i=0, average;
student= malloc(sizeof(struct person));
//struct person student;
printf("Enter the following information:\n");
while (i<size) {
printf("%lf\n%lf\n",total,i);
printf("\n");
printf("Name:");
scanf("%s",student->Name);
printf("ID:");
scanf("%d",&student->ID);
printf("Age:");
scanf("%d",&student->Age);
printf("Score:");
scanf("%lf",&student->Score);
total = total + student->Score;
i++;
}
代碼工作正常,直到它需要根據用戶輸入打印出平均值,此時程序終止而不給出平均值或錯誤消息。
if(size==1){
average = total / size;
printf("Class average is %0.2lf\n", average);
}
else
{
average=total/i;
printf("Class average is %0.2lf\n", average);
}
return 0;
}
大多數控制台程序都旨在從某種控制台主機上運行,例如 windows cmd,其中 output 停留在那里,因為結束程序會很煩人,因此用戶可以運行另一個命令,但他們可以執行一些額外的工作只是測試一下,你應該在最后放一些代碼來等待一些用戶輸入,現在有很多方法可以做到這一點:getch()、getchar()、scanf("%*c")、system("pause ") 所以你可以嘗試這些,但有些編譯器會在調試模式下自動執行此操作,有時你只需要在 IDE 設置中指定行為。
我認為您遇到的問題是控制台正在關閉,然后您才能讀取平均值。
您可以添加:
獲取字符();
返回 0 之前; 在 int 主要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.