有5个学生,每个学生数据包括学号、姓名和成绩,要求分别用3个函数实现以下功能:
用input函数输入所有学生数据
用sort函数将学生数据按照成绩由高到低排序后输出
用max函数找到成绩最高学生并输出其信息
这是我写的:
#include
#define N 5
struct Student
{
char name[20];
int num;
int score;
};
int main()
{
void input(struct Student stu[]);
void sort(struct Student stu[]);
struct Student max(struct Student stu[]);
struct Student stu[N], * p = stu;
struct Student stud;
input(p);
sort(p);
stud = max(p);
printf("成绩最高的学生是:\n");
printf("学号:%d\n姓名:%s\n成绩:%d\n", stud.num, stud.name, stud.score);
return 0;
}
void input(struct Student stu[])
{
int i;
printf("请输入五名学生的信息:(姓名、学号、成绩)\n");
for (i = 1; i < N; i++)
{
gets_s(stu[i].name);
scanf_s("%d%d", &stu[i].num, &stu[i].score);
}
}
void sort(struct Student stu[])
{
int n[5] = { stu[1].score,stu[2].score ,stu[3].score ,stu[4].score ,stu[5].score };
for (int i = 0; i < 4; i++)
{
for (int a = 0; a < 5 - 1 - i; a++)
{
if (stu[a].score > stu[a + 1].score)
{
int t = stu[a].score;
stu[a].score = stu[a + 1].score;
stu[a + 1].score = t;
}
}
}
for (int i = 0; i < 5; i++)
printf("%d\n", n[i]);
}
struct Student max(struct Student stu[])
{
int i, m = 0;
for (i = 0; i < N; i++)
if (stu[i].score > stu[m].score)
m = i;
return(stu[m]);
}
可是运行起来完全不正常啊,我刚接触c语言,上网搜也搜不到相关东西(也可能我搜到了但是我没看懂)
你这代码错误一大堆
1.索引从0开始,stu[5].score都越界了呀
2.要求你排序学生,你怎么只交换分数不交换姓名,那不全乱了吗
3.max函数要求排序后输出,你怎么把输出放到max函数外面了
修改如下,改动处见注释,供参考:
#include <stdio.h>
#define N 5
struct Student
{
char name[20];
int num;
int score;
};
int main()
{
void input(struct Student stu[]);
void sort(struct Student stu[]);
struct Student max(struct Student stu[]);
struct Student stu[N], * p = stu;
struct Student stud;
input(p);
sort(p);
stud = max(p);
printf("成绩最高的学生是:\n");
printf("学号:%d\n姓名:%s\n成绩:%d\n", stud.num, stud.name, stud.score);
return 0;
}
void input(struct Student stu[])
{
int i;
printf("请输入五名学生的信息:(姓名、学号、成绩)\n");
for (i = 0; i < N; i++) //for (i = 1; i < N; i++) 修改
{
//gets_s(stu[i].name, 20); 修改
scanf_s("%s%d%d", stu[i].name, 20, &stu[i].num, &stu[i].score); //修改
}
}
void sort(struct Student stu[])
{
//int n[5] = { stu[1].score,stu[2].score ,stu[3].score ,stu[4].score ,stu[5].score }; 修改
struct Student tmp; //修改
for (int i = 0; i < N - 1; i++) //for (int i = 0; i < 4; i++) 修改
{
for (int a = 0; a < N - 1 - i; a++) //for (int a = 0; a < 5 - 1 - i; a++) 修改
{
if (stu[a].score < stu[a + 1].score) //(stu[a].score > stu[a + 1].score) 修改
{
tmp = stu[a]; //int t = stu[a].score; 修改
stu[a] = stu[a + 1]; //stu[a].score = stu[a + 1].score; 修改
stu[a + 1] = tmp; //stu[a + 1].score = t; 修改
}
}
}
for (int i = 0; i < N; i++) //(int i = 0; i < 5; i++) 修改
printf("%d %s %d \n", stu[i].num, stu[i].name, stu[i].score);
}
struct Student max(struct Student stu[])
{
int i, m = 0;
for (i = 0; i < N; i++)
if (stu[i].score > stu[m].score)
m = i;
return(stu[m]);
}