声明:该编译器为vs,所以输入函数写为scanf_s形式!
代码如下:
#include <stdio.h>
#define N 40
int 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;
}
运行结果如下: