Làm thế nào để xử lý ngoại lệ khi nhập ký tự vào IDs với điểm của học sinh
#include <stdio.h>
#include <stdlib.h>
//Define a function to input the grades and IDs
void Input(float a[],int b[],int i, int n)
{
for(i=0;i<n;i++){
do{
printf("Input ID student number %d: ", i+1);
scanf("%d",&b[i]);
if(b[i]>0)
break;
else{
printf("The IDs of student must be positive and not allow enter character. Please input again!!!\n");
getch();
}
}while(1);
do{
printf("Input grade student number %d: ", i+1);
scanf("%f",&a[i]);
if(a[i]>=0 && a[i]<=10){
break;
}
else{
printf("the value must be in range[1,10]. Please input again!!! \n");
getch();
}
}while(1);
}
}
//Define a function to check max grade
float max(float a[], int n)
{
float max = a[0];
for (int i = 0; i < n; i++)// i < n
if (max < a[i])
max = a[i];
return max;
}
//Define a function to find the index in max
int find_max_index(float a[],int n){
int i, index=0;
float max=a[0];
for(i=1;i<n;i++)
if(max<a[i]){
max=a[i];
index=i;
}
return index;
}
//Define a function to find the index in min
int find_min_index(float a[], int n){
int i,index;
index=0;
float min;
min=a[0];
for(i=1;i<n;i++)
if(min>a[i]){
min=a[i];
index=i;
}
return index;
}
//Define a function to check min grade
float min(float a[], int n)
{
float min = a[0];
for (int i = 0; i < n; i++){ //i = 0; i < n
if (min > a[i]){
min = a[i];
}
return min;
}
}
int main()
{
float a[100];//grade
int b[100];//ID
int n,i,m;
printf("\n\t\t==========STUDENT TRANSCRIPTS==========");
printf("\nInput the number of student: ");
do{
scanf("%d",&n);
if(n>0){
break;
}
else
printf("\nThe number of student must be positive. Please input again ");
}while(n<0);
Input(a,b,i,n);
do{
system("cls");
printf("\n\t\t==========MENU==========");
printf("\n\t\t 1. List IDS students and Grades");
printf("\n\t\t 2. Display highest grade student");
printf("\n\t\t 3. Display lowest grade student");
printf("\n\t\t 4. Exit");
printf("\n\t\t======================");
printf("\n\t\t Please choose the menu: ");
//Choose option
scanf("%d",&m);
switch(m){
case 1:
printf("\n\t\t IDS students and Grades");
for(i=0;i<n;i++){
printf("\n\t\t ID student %d: %d",i+1,b[i]);
printf("\n\t\t Grade: %.2f",a[i]);
}
getch();
break;
case 2:
printf("\nThe student with IDs %d is a student has highest grade is %.2f ",b[find_max_index(a,n)], max(a, n));
getch();
break;
case 3:
printf("\nThe student with IDs %d is a student has lowest grade is %.2f",b[find_min_index(a,n)] ,min(a, n));
getch();
break;
case 4:
printf("\n\t\t See you again !!!");
getch();
exit(0);
default:
printf("Invalid number. Please choose from 1 to 4");
getch();
break;
}
getch();
}while (n!=4);
return 0;
}