我正在开始C语言课程,特别是功能。我的任务是按数值对数组的结构进行排序,在这种情况下,该值是变量'age。'
我不确定我应该如何制作正确的论据以及从哪里开始。一些指导将不胜感激。提前致谢。
#include <stdio.h>
#include <stdlib.h>
#define STUDENTS 5 //Maximum number of students to be saved.
#define LENGTH 20 //Maximum length of names.
struct person { //Setting up template for 'person'
char first[LENGTH];
char last[LENGTH];
int age;
};
void bubblesort(int, int); //Prototyping function for sorting structures.
int main(void) {
struct person student[STUDENTS] = { //Array of person structures.
{"Person", "One", 21},
{"Person", "Two", 18},
{"Person", "Three",20},
{"Person", "Four", 17},
{"Person", "Five", 16}
};
int i; //For loop counter.
int n=5; //For loop variable. N is equal to the # of entries in the struct.
printf("Here is an unsorted list of students: \n");
for( i=0; i<n; i++) {
printf("%s %s is %d years old. \n", student[i].first, student[i].last, student[i].age);
}
//Sort students by age.
//Print sorted list.
return 0;
}
答案 0 :(得分:0)
如果要根据字段年龄对结构数据进行排序,则可以使用以下代码
struct person temp;
for(i=0; i<STUDENTS; i++)
{
for(j=i; j<STUDENTS; j++)
{
if(stud[i].age < stud[j].age)
{
temp = stud[i];
stud[i] = stud[j];
stud[j] = temp;
}
}
}
为了实现这一目标,您可以通过引用传递结构,如下所示,
void bubble(struct person * stud);
该函数的原型是void bubble(struct person *);