1

我正在尝试对成绩使用排序功能,它将对“姓名中期1”进行排序,但我不知道如何将姓名和姓氏字符串分配给临时数组。有任何想法吗?

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
4

2 回答 2

3

不应该是:

    strcpy (temp2,x[y+1].name);
    strcpy (x[y+1].name,x[y].name);
    strcpy (x[y].name,temp2);    // <-- note the index used

?

姓氏也是如此。

于 2012-08-09T15:25:52.693 回答
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;
}
于 2012-08-09T15:51:44.830 回答