200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > C语言 利用一维数组中选择法对成绩高低排序和输出对应的学号及利用顺序查找查找学生

C语言 利用一维数组中选择法对成绩高低排序和输出对应的学号及利用顺序查找查找学生

时间:2021-10-01 11:25:53

相关推荐

C语言 利用一维数组中选择法对成绩高低排序和输出对应的学号及利用顺序查找查找学生

声明:该编译器为vs,所以输入函数写为scanf_s形式!

代码如下:

#include <stdio.h>#define N 40int ReadScore(int score[], long num[]);//函数原型;void DataSort(int score[], int n, long num[]);//函数原型;void PrintfScore(int score[], int n, long num[]);//函数原型;int LinSearch(long num[], long x, int n); //函数原型;int main() {int score[N], n,pos;//pos为查找学生成绩的下标位置;long num[N],x;//x为所要查找的学生学号;n = ReadScore(score, num);printf("Total students are %d\n", n);printf("Input the searching ID:");scanf_s("%ld", &x);pos= LinSearch(num,x, n);if (pos != -1) { printf("score=%d\n", score[pos]); }else { printf("Not found\n"); }DataSort(score, n, num);printf("Sorted scores:\n");PrintfScore(score, n, num);return 0;}//函数功能:读入该门课的成绩:int ReadScore(int score[], long num[]) {int i = -1;printf("Input student't ID and score:\n");do {i++;scanf_s("%ld %d", &num[i], &score[i]);} while (num[i] > 0 && score[i] >= 0);return i;}//函数功能:将该门课的成绩按照高低排序;void DataSort(int score[], int n, long num[]) {int i, j, temp1, k;long temp2;for (i = 0; i < n - 1; i++) {k = i;for (j = i + 1; j < n; j++) {if (score[j] > score[k]) {k = j;//记录最大的下标位置}}if (k != i) {//若最大数的下标位置不在下标位置i;temp1 = score[k]; score[k] = score[i]; score[i] = temp1;temp2 = num[k]; num[k] = num[i]; num[i] = temp2;}}}//函数功能:打印该门课的成绩;void PrintfScore(int score[], int n, long num[]) {int i;for (i = 0; i < n; i++) {printf("%d%4d\n", num[i], score[i]);}}//按照线性查找法查找值为x,若找到则返回X的在数组中的下标位置,否则返回-1;int LinSearch(long num[], long x, int n) {int i;for (i = 0; i < n; i++) {if (num[i] == x) { return i; }}return -1;}

运行结果如下:

C语言 利用一维数组中选择法对成绩高低排序和输出对应的学号及利用顺序查找查找学生成绩

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。