解題思路:
用結構體數組存放n個學生資訊,采用選擇法對各元素進行排序(進行比較的是各元素中的成績)
頭檔案
#include<stdio.h>
#include<stdlib.h>
建立結構體,把一個學生的資訊(姓名、學号、成績)放在一個結構體變量中
typedef struct Student
{
char name[20];//姓名
char id[12];//學号
double score;//成績
}Student;
輸入函數
void Input(struct Student* arr, int len)
{
for (int i = 0; i < len; i++)
{
scanf_s("%s %s %lf", &arr[i].name, 20, &arr[i].id, 12, &arr[i].score);
}
}
排序函數
void Show(struct Student* arr, int len)
{
for (int i = 0; i < len; i++)
{
printf("%s %s %lf\n", arr[i].name, arr[i].id, arr[i].score);
}
}
輸出函數
void Sort(struct Student* arr, int len)
{
for (int i = 0; i < len; i++)
{
for (int j = 0; j + 1 < len - i; j++)
{
if (arr[j].score < arr[j + 1].score)//存在誤差
{
struct Student tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
主函數
int main()
{
int n;
printf("請輸入要輸入的學生人數:\n");
scanf_s("%d", &n);
struct Student* arr = (struct Student*)malloc(n * sizeof(struct Student));
Input(arr, n);
Sort(arr, n);
Show(arr, n);
//以上是學生人數由鍵盤輸入,以下是再主函數中已經确定人數
//struct Student arr[3];
//Input(arr, sizeof(arr) / sizeof(arr[0]));
//Sort(arr, sizeof(arr) / sizeof(arr[0]));
//Show(arr, sizeof(arr) / sizeof(arr[0]));
return 0;
}