c語言 結構體-按姓名排序 (上課用)


源程序:

#include <stdio.h>
#include <string.h>
#define N 5

struct student //數據類型
{
int num; //學號
char sname[25]; //姓名
char sex[4]; //性別
int age; //年齡
};

struct student stu[N]={
{1008,"張佳欣","女",18},
{1001,"趙文彬","男",19},
{1005,"陳敏芳","女",17},
{1010,"吳力維","男",20},
{1009,"吳澤林","男",21}
};

//按姓名排序
void sort(struct student stud[],int n)
{
int i,j;
struct student temp; //臨時結構體變量
for(i=0;i<n;i++) //行
{
for(j=0;j<n-i-1;j++) //列
{
if(strcmp(stud[j].sname,stud[j+1].sname)>0)
{
temp=stud[j];
stud[j]=stud[j+1];
stud[j+1]=temp;

}
}
}
}

void main()
{
int i;
printf(" 學號 姓名 年齡\n");
printf("---------------------------\n");
sort(stu,N);
for(i=0;i<N;i++)
printf("%5d%10s%8d\n",stu[i].num,stu[i].sname,stu[i].age);
}

 

 運行結果 :

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM