#include<stdio.h>
#define N 10
int ReadScore(int score[],long num[]);
int Linsearch(long num[],long x,int n);
int main()
{
int score[N],n,pos;
long num[N],x;
n=ReadScore(score,num);//写入学号和成绩,直到输入不合法
printf("Total students are %d\n",n);//打印有效人数
printf("Input the searching ID:");//输入想查询的学号
scanf("%d",&x);
pos=Linsearch(num,x,n);//查找该学生
if(pos!=-1)//成功找到
printf("score=%d\n",score[pos]);
else //没有找到
printf("NOt Found!\n");
return 0;
}
int ReadScore(int score[],long num[])
{
int i=-1;
do
{
i++;
printf("Input student's ID and score:");
scanf("%ld%d",&num[i],&score[i]);//写入每一个学生的成绩和学号
}while(num[i]>0 && score[i]>=0);//成绩小于0或者学号不大于0时退出
return i;
}
int Linsearch(long num[],long x,int n)
{
int i;
for(i=0;i<n;i++)
{
if(num[i]==x)
return i;//查找成功,返回下标
}
return -1;
}
代码运行1:
Input student's ID and score:2018001 98
Input student's ID and score:2018002 95
Input student's ID and score:2018003 85
Input student's ID and score:2018004 94
Input student's ID and score:2018005 78
Input student's ID and score:0 0
Total students are 5
Input the searching ID:2018002
score=95
代码运行2:
Input student's ID and score:2018001 95
Input student's ID and score:2018002 93
Input student's ID and score:2018003 94
Input student's ID and score:2018004 75
Input student's ID and score:0 0
Total students are 4
Input the searching ID:2018005
NOt Found!