参考書に書いてある「構造体を使って身長の昇順にソートする」というコードなのですが、sort_by_heightのfor文(2つとも)の意味がよくわかりません。特に、jが何を表すのかわかりません。
また、#include <string.h>はなぜ必要なのでしょうか。
調べたところ、これを必要とする関数などは使っていないと感じました。
質問が抽象的で申し訳ありません。
教えていただけたらありがたいです。
c
1#include<stdio.h> 2 #include<string.h> 3 4 #define NUMBER 5 5 #define NAME_LEN 64 6 7 /*学生を表す構造体*/ 8 typedef struct { 9 char name[NAME_LEN]; 10 int height; 11 float weight; 12 long schols; 13 }Student; 14 15 /*---xおよびyが指す学生を交換---*/ 16 void swap_Student(Student * x, Student *y) 17 { 18 Student temp = *x; 19 *x = *y; 20 *y = temp; 21 } 22 23 /*--- 学生の配列aの先頭n個の要素を身長の昇順にソート ---*/ 24 void sort_by_height(Student a[], int n) 25 { 26 int i, j; 27 for (i = 0; i<n - 1; i++){ 28 for (j = n - 1; j>i; j--) 29 if (a[j - 1].height>a[j].height) 30 swap_Student(&a[j - 1], &a[j]); 31 } 32 } 33 34 int main(void) 35 { 36 int i; 37 Student std[] = { 38 { "Sato", 178, 61.2, 80000 }, 39 { "Sanaka", 175, 62.5, 73000 }, 40 { "Takao", 173, 86.2, 0 }, 41 { "Mike", 165, 72.3, 70000 }, 42 { "Masaki", 179, 77.5, 70000 }, 43 }; 44 45 for (i = 0; i<NUMBER; i++) 46 printf("%-8s %6d%6.1f%7ld\n", 47 std[i].name, std[i].height, std[i].weight, std[i].schols); 48 49 sort_by_height(std, NUMBER); /*身長の昇順にソート*/ 50 51 puts("\n身長の昇順にソートしました。"); 52 for (i = 0; i<NUMBER; i++) 53 printf("%-8s %6d%6.1f%7ld\n", 54 std[i].name, std[i].height, std[i].weight, std[i].schols); 55 56 return 0; 57}
回答2件
あなたの回答
tips
プレビュー