#include<stdio.h>
#include<stdlib.h>
#define SIZE 200
//第四题
int readData(int a[], int b[]);
void sort(int a[], int b[], int len);
int search(int a[], int len, int id);
int main()
{
int num[SIZE], score[SIZE]; //分别保存学号和成绩
int count; //代表学生人数
int index; //代表查找到的学生的下标
int key;
count = readData(num, score); //将成绩数据从文件中读到数组中
for (int i = 0; i < count; i++)
printf("%d\t%d\n", *(num+i), *(score+i));
printf("%d", count);
while (1)
{
printf("请输入要查找的学生学号(输入0退出查询程序):");
scanf("%d", &key);
if (key == 0)
{
printf("查询程序退出,欢迎您的使用。\n");
break;
}
index = search(num, count, key); //在count个学生中查找学号为key的学生对应的下标
if (index < 0) //输入的学号不存在时,index的值要求返回-1
printf("不存在学号为%d的同学\n", key);
else
printf("学号为%d的同学的成绩是:%d\n", key, score[index]);
}
return 0;
}
int readData(int num[], int score[])
{
FILE *fp;
int i,count=0;
fp = fopen("score1.txt", "r");
if (fp == NULL)
{
printf("打开文件失败\n");
exit(1);//exit(1)表示异常退出,exit(0)为正常退出
}
for (i = 0; i < SIZE; i++)
{
if (fscanf(fp, "%d\t%d", num + i, score + i) != EOF)//文件读取到最后一行自动结束
count++;
else
break;
}
sort(num, score,count);
return count;
}
void sort(int num[], int score[], int len)
{
int i,j,temp;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - i - 1;j++)
if (num[j]>num[j + 1])//以学号为排序主键,成绩和学号一起移动
{
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
temp = score[j];
score[j] = score[j + 1];
score[j + 1] = temp;
}
}
int search(int num[], int len, int id)
{
int low = 0, high = len - 1;
int mid;
int index;
while (low < high)
{
mid = (low + high) / 2;
if (num[mid] == id)
{
index = mid;
return index;
}
else if (num[mid] > id)
high = mid - 1;
else
low = mid + 1;
}
index = -1;
return index;
}