|
今ソートさせるプログラムを作ったのですが、名前は上手くソートされるのですが、背番号、身長、体重がうまくソートされません。
どこが違うのかアドバイスお願いします。
あと身長に関しては、体重と同じようにしているつもりなのですが、
エラーがでてしまうんです。なので今はコメント化しているのですが・・・
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[100]; /* 名前 */
int num; /* 背番号 */
int weight; /* 体重 */
int height; /* 身長 */
} person;
/*比較関数(名前昇順)*/
int npcmp(const person *x, const person *y)
{
return (strcmp(x->name, y->name));
}
/*比較関数(背番号昇順)*/
int numpcmp(const person *x, const person *y)
{
return (x->num < y->num ? -1 :
x->num < y->num ? 1 : 0);
}
/*比較関数(体重降順)*/
int wdcmp(const person *x, const person *y)
{
return (x->weight < y->weight ? 1 :
x->weight < y->weight ? -1 : 0);/* 降順 */
}
/*比較関数(身長降順)*/
/*int hpcmp(const person *x,const person *y)
{
return (x->height < y->height ? 1:
x->height < y->height ? -1 : 0);
}
*/
/*一人分のデータを表示*/
void print_person(person x)
{
printf("%-20.20s NO.%d %dkg %dcm\n", x.name, x.num, x.weight, x.height);
}
int main(void)
{
int i;
person x[]= {{"Mitsuo Ogasawara", 8, 72, 173},
{"Seigo Narazaki", 1, 76, 185},
{"Naoki Matsuda", 3, 78, 183},
{"Tsuneyasu Miyamoto", 5, 72, 176},
{"Yuji Nakazawa", 22, 78, 187},
{"Alessandro Santos", 14, 69, 178},
{"Akira Kaji", 21, 67, 175},
{"Koji Nakata", 6, 74, 182},
{"Yuki Abe", 30, 68, 175},
{"Takayuki Suzuki", 11, 75, 182},
{"Keiji Tamada", 28, 67, 173},
};
int nx = sizeof(x) / sizeof(x[0]); /* 配列xの要素数 */
puts("ソート前");
for (i = 0; i < nx; i++)
print_person(x[i]);
/* 名前昇順にソート */
qsort(x, nx, sizeof(person), (int(*)(const void*, const void*))npcmp);
puts("\n名前昇順ソート後");
for (i = 0; i < nx; i++)
print_person(x[i]);
/* 背番号昇順にソート */
qsort(x, nx, sizeof(person), (int(*)(const void*, const void*))numpcmp);
puts("\n背番号昇順ソート後");
for (i = 0; i < nx; i++)
print_person(x[i]);
/* 体重降順にソート */
qsort(x, nx, sizeof(person), (int(*)(const void*, const void*))wdcmp);
puts("\n体重降順ソート後");
for (i = 0; i < nx; i++)
print_person(x[i]);
/* 身長降順にソート */
/* qsort(x, nx, sizeof(person), (int(*)(const void*, const void*))hpcmp);
puts("\n身長降順ソート後");
for (i = 0; i < nx; i++)
print_person(x[i]);
*/
return (0);
}
|