提高篇26-27课第四题
2015-06-01 18:57
369 查看
#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; }
相关文章推荐
- 黑马程序员——交通灯管理系统
- MFC六大核心机制之五、六:消息映射和命令传递
- cdoj 03 BiliBili, ACFun… And More! 水题
- MFC六大核心机制之四:永久保存(串行化)
- Linux系统编程——进程间通信:信号中断处理
- 作业6--超级无敌终结(冲刺二)
- Docker生态系统系列之一:常用组件介绍
- 指针与数组用法笔记
- 【iOS百度地图系列_1】在地图上定位当前位置
- 【palindrome partitioning II】cpp
- 怎样让外界无法改变自定义view的尺寸大小
- cglib动态代理简单的例子
- MFC六大核心机制之三:动态创建
- MFC六大核心机制之二:运行时类型识别(RTTI)
- EntityFramework5.0 批量插入错误
- IOS-UIMenuController 和 UIResponderStandardEditActions
- xcode6制作静态库详解
- OC视频笔记(不可变字典常用方法,与优化方法)(可变字典的常用方法)
- 网页html中嵌入特殊字体
- border-radius