题目:从键盘读取n个学生的信息(包括学号,姓名,成绩),然后按成绩的高低顺序输出:
分析:①读取信息②排序③显示信息
思路:用结构体数组存放n个学生的成绩,采用冒泡法进行排序。
#include<stdio.h>
#include<malloc.h>
typedef struct Student
{
char num[20];
char name[20];
float score;
}stud;//stud就相当于int
void Input(stud* stu, int len)
{
for (int i = 0; i < len; i++)
{
printf("请输入第%d位同学的成绩\n", i + 1);
scanf_s("%s %s %f", &stu[i].num, 20, &stu[i].name, 20, &stu[i].score);
}
}
void sort(stud* stu, int len)
{
for (int i = 0; i < len-1; i++)//趟数
{
for (int j = 0; j < len- i-1; j++)//比较数
{
if (stu[j].score < stu[j + 1].score)
{
stud tmp = stu[j];
stu[j] = stu[j + 1];
stu[j + 1] = tmp;
}
}
}
}
void Output(stud* stu,int len)
{
for (int i = 0; i < len; i++)
{
printf("学号:%s 姓名:%s 成绩:%5.1f\n", stu[i].num,stu[i].name, stu[i].score);
}
}
int main()
{
printf("请输入学生的个数:\n");
int n;
scanf_s("%d", &n);
stud* stu = (stud*)malloc(sizeof(stud)* n);
Input(stu, n);
sort(stu,n);
Output(stu, n);
return 0;
}
在编辑过程中我犯的错误;
①我将学号定义成字符串类型,起初定义的是十个,后来输入了十个数字,忽略了‘\0’,导致越界。
②使用malloc时,可以直接使用‘sizeof(结构体)’。
如有错误,欢迎批评指正!!!