#include
struct student
{
char szName[100];
float score1; // 课程1成绩
float score2; // 课程2成绩
float score3; // 课程3成绩
float score4; // 课程4成绩
float avgSocre; // 平均成绩
// 等号重载
student operator=(student &st)
{
sprintf(szName, st.szName);
score1 = st.score1;
score2 = st.score2;
score3 = st.score3;
score4 = st.score4;
avgSocre = st.avgSocre;
return *this;
}
// 输出学生信息以及分数
void printfStu()
{
printf("%s\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\n", szName, score1, score2, score3, score4,avgSocre);
}
};
int main()
{
const int stuCount = 3;
student stuArray[stuCount];
printf("姓名\t课程1成绩\t课程2成绩\t课程3成绩\t课程4成绩\n");
for (int i = 0; i < stuCount; i++)
{
scanf("%s %f %f %f %f",
stuArray[i].szName,
&stuArray[i].score1,
&stuArray[i].score2,
&stuArray[i].score3,
&stuArray[i].score4);
stuArray[i].avgSocre = (stuArray[i].score1 + stuArray[i].score2 +
stuArray[i].score3 + stuArray[i].score4 )/4;
}
// 排序
for (int i = 0; i < stuCount; i++)
{
for (int j = 0; j < stuCount - i -1; j++)
{
if (stuArray[j + 1].avgSocre < stuArray[j].avgSocre)
{
student stu = stuArray[j];
stuArray[j] = stuArray[j + 1];
stuArray[j + 1] = stu;
}
}
}
// 打印
printf("姓名\t课程1成绩\t课程2成绩\t课程3成绩\t课程4成绩\t平均成绩\n");
for (int i = 0 ; i < stuCount; i ++)
{
stuArray[i].printfStu();
}
return 0;
}
运行结果如下:
#include
main()
{
float stu[3][5], temp; // 3个学生4门课加平均分的成绩
int i, j, k;
for(i = 0; i < 3; i++) {
printf("输入第%d个学生的四门课成绩: ", i+1);
for(j = 0; j < 4; j++)
scanf("%f", &stu[i][j]);
stu[i][4] = (stu[i][0] + stu[i][1] + stu[i][2] + stu[i][3]) / 4; // 求平均分
}
// 按平均成绩进行升序排序
for(i = 0; i < 2; i++)
for(j = i+1; j < 3; j++) {
if(stu[i][4] > stu[j][4]) {
for(k = 0; k < 5; k ++) {
temp = stu[i][k];
stu[i][k] = stu[j][k];
stu[j][k] = temp;
}
}
}
// 输出排序后的成绩
for(i = 0; i < 3; i++) {
for(j = 0; j < 5; j++)
printf("%-5.1f ", stu[i][j]);
printf("\n");
}
}