这是一个程序,它计算每个学生的分数并对总数进行排序,但不交换其他参数(例如学生姓名和他们的科目分数)的顺序。如何对结构进行整体排序,同时保留总分作为排序依据?我不想使用任何内置函数,而是通过基本方法来完成。
#include<stdio.h>
#include<conio.h>
struct stnd
{
int sub[20];
char name[20];
int total;
}
stnd[20];
main()
{
int i, j, n=4, m=4,k;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
scanf("%d",&stnd[i].sub[j]);
for(i=0; i<n; i++)
scanf(" %s",stnd[i].name);
for(i=0; i<n; i++)
{
stnd[i].total=0;
for(j=0; j<m; j++)
stnd[i].total=stnd[i].total+stnd[i].sub[j];
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(stnd[i].total<stnd[j].total)
{
k=stnd[i].total;
stnd[i].total=stnd[j].total;
stnd[j].total=k;
}
}
}
printf("Rank\t Chin\t Math\t Eng\t Comp\t total\t name\n");
for(i=0; i<n; i++)
{
printf("%d\t",i+1);
for(j=0; j<m; j++)
printf("%d\t",stnd[i].sub[j]);
printf("%d\t",stnd[i].total);
printf("%s\t\n",stnd[i].name);
}
getch();
}
最佳答案
在你要交换的函数中,只交换结构而不是总数:
// Where you declare k, declare it as a struct stnd
struct stnd k;
// Where you swap, just swap the structures, not the totals
k = stnd[i];
stnd[i] stnd[j];
stnd[j] = k;
当您设置struct stnd
时,它会按位复制您正在复制的对象,这正是您排序所需要的。
关于c++ - 使用基本方法对结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19582341/