提高篇26-27课第四题

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值