我正在尝试使用等级的排序功能,它将对姓氏midterm1"进行排序,但我无法想象如何将名称和姓氏字符串分配给临时数组。有什么想法吗?
void student_swap(struct student *x){
int z,y,temp;
char temp2[15];
for(z=0; z<10; z++){
for(y=0; y<9; y++){
if(x[y].mid1>x[y+1].mid1){
temp = x[y+1].mid1;
x[y+1].mid1 = x[y].mid1;
x[y].mid1 = temp;
strcpy (temp2,x[y+1].name);
strcpy (x[y+1].name,x[y].name);
strcpy (x[y+1].name,temp2);
strcpy (temp2,x[y+1].surname);
strcpy (x[y+1].surname,x[y].surname);
strcpy (x[y+1].surname,temp2);
} // if
} // for
} // for
} //student_swap
排序int
值工作正常,但strcpy
什么都不做。
这是我的输出代码
for (i=9;i>=0;i--){
;
printf ("%s %s %d\n",x[i].name,x[i].surname,x[i].mid1);
}
printf ("\n");
student_swap(x);
for (i=9;i>=0;i--){
;
printf ("%s %s %d\n",x[i].name,x[i].surname,x[i].mid1);
}
这是我的输出
murat hot 73
mehmet umur 72
idil saracoglu 55
ecem bektas 75
sevde pir 70
asli devecioglu 65
can akkurt 45
levent dogan 60
anil erdiz 30
ali durmus 40
murat hot 75
mehmet umur 73
idil saracoglu 72
ecem bektas 70
sevde pir 65
asli devecioglu 60
can akkurt 55
levent dogan 45
anil erdiz 40
ali durmus 30
答案 0 :(得分:3)
不应该是:
strcpy (temp2,x[y+1].name);
strcpy (x[y+1].name,x[y].name);
strcpy (x[y].name,temp2); // <-- note the index used
同样的姓氏。
答案 1 :(得分:0)
在学习编程时自己实施排序是很好的练习。但是,在编写生产代码时,最好避免重新发明轮子。例如,您可以使用随qsort
提供的stdlib.h
:
#include <stdio.h>
#include <stdlib.h>
struct student { char name[100]; char surname[100]; int mid1;};
int compare_students (const void *a, const void *b)
{
struct student *sa, *sb;
sa = (struct student *) a;
sb = (struct student *) b;
if (sa->mid1 > sb->mid1)
return -1;
if (sa->mid1 == sb->mid1)
return 0;
return 1;
}
int main (void)
{
int i;
struct student s[4] = {
{.name = "a", .surname = "e", .mid1 = 10},
{.name = "b", .surname = "f", .mid1 = 20},
{.name = "c", .surname = "g", .mid1 = 99},
{.name = "d", .surname = "h", .mid1 = 70}
};
qsort (s, 4, sizeof (struct student), compare_students);
for (i = 0; i < 4; i++)
printf ("%s %s: %d\n", s[i].name, s[i].surname, s[i].mid1);
return 0;
}