结构体,按照名姓名升序输出
本帖最后由 LukaDoncicY77 于 2021-12-15 18:42 编辑#include <stdio.h>
#include <string.h>
struct men
{
int id;
char name;
char tel;
int mpoints;
};
int main()
{
int i,j;
struct men t;
struct men mem={
{1,"Lihong","123",789},
{4,"ZhaoHan","123",789},
{2,"QianQi","123",789},
{5,"ZhouHe","123",789},
{3,"SunHai","123",789}
};
for(i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
if(strcmp(mem.name,mem.name)>0)
{t=mem;mem=mem;mem=t;}
}
printf("\n");
for(i=0;i<5;i++)
printf("%6d%20s%15s%6d\n",mem.id,mem.name,mem.tel,mem.mpoints);
return 0;
}
我的排序法 应该如何修改?
for(i=0;i<4;i++)
{
for(j=i+1;j<5;j++)
if(strcmp(mem.name,mem.name)>0)
{t=mem;mem=mem;mem=t;}
}
printf("\n");
已解决。
大家能否帮忙看一下 下面这个 选择排序法我不太理解
for(i=1;i<5;i++)
{
int k=5-i
for(j=0;j<5-i;j++)
if(strcmp(mem.name,mem.name)>0)
k=j;
if(k!=5-i)
{
t=mem;mem=mem;mem=t;
}
} #include <stdio.h>
#include <string.h>
struct men
{
int id;
char name;
char tel;
int mpoints;
};
int main(void)
{
int i,j;
struct men t;
struct men mem={
{1,"Lihong","123",789},
{4,"ZhaoHan","123",789},
{2,"QianQi","123",789},
{5,"ZhouHe","123",789},
{3,"SunHai","123",789}
};
for(i = 0 ; i < 4 ; i ++)
{
for(j = i + 1 ; j && strcmp(mem . name , mem . name) < 0 ; j --) {
t = mem ;
mem = mem ;
mem = t ;
}
}
printf("\n");
for(i=0;i<5;i++)
printf("%6d%20s%15s%6d\n",mem.id,mem.name,mem.tel,mem.mpoints);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int id;
char name, tel;
int mpoints;
}m;
int compare (const void *a, const void *b){
m *A = (m*)a;
m *B = (m*)b;
return strcmp(A->name, B->name) > 0 ? 1 : -1;
}
int main(){
m arr = {
{1, "Lihong", "123", 789},
{4, "ZhaoHan", "123", 789},
{2, "QianQi", "123", 789},
{5, "ZhouHe", "123", 789},
{3, "SunHai", "123", 789}};
qsort(arr, 5, sizeof(*arr), compare);
for(int i = 0; i < 5; i++) printf("%6d%20s%15s%6d\n", arr.id, arr.name, arr.tel, arr.mpoints);
return(0);
}
页:
[1]