C言語構造体とアルゴリズムの実践的演習

4、演習課題4

task4.cソースコードと実行結果:

 1 #include <stdio.h>
 2 #define MAX_BOOKS 10
 3 
 4 typedef struct {
 5     char book_id[20];        // 書籍ID
 6     char title[80];          // タイトル
 7     char writer[80];        // 著者
 8     double price;            // 価格
 9     int  quantity;          // 売上数量
10 } Publication;
11 
12 void display_books(Publication books[], int size);
13 void arrange_by_quantity(Publication books[], int size);
14 double calculate_revenue(Publication books[], int size);
15 
16 int main() {
17     Publication catalog[MAX_BOOKS] = {
18         {"978-7-5327-6082-4", "门将之死", "罗纳德.伦", 42, 51},
19         {"978-7-308-17047-5", "自由与爱之地:入以色列记", "云也退", 49, 30},
20         {"978-7-5404-9344-8", "伦敦人", "克莱格泰勒", 68, 27},
21         {"978-7-5447-5246-6", "软件体的生命周期", "特德姜", 35, 90}, 
22         {"978-7-5722-5475-8", "芯片简史", "汪波", 74.9, 49},
23         {"978-7-5133-5750-0", "主机战争", "布莱克.J.哈里斯", 128, 42},
24         {"978-7-2011-4617-1", "世界尽头的咖啡馆", "约翰·史崔勒基", 22.5, 44},
25         {"978-7-5133-5109-6", "你好外星人", "英国未来出版集团", 118, 42},
26         {"978-7-1155-0509-5", "无穷的开始:世界进步的本源", "戴维·多伊奇", 37.5, 55},
27         {"978-7-229-14156-1", "源泉", "安.兰德", 84, 59}
29     };
30     
31     printf("書籍売上ランキング(数量順): \n");
32     arrange_by_quantity(catalog, MAX_BOOKS);
33     display_books(catalog, MAX_BOOKS);
34 
35     printf("\n総売上高: %.2f\n", calculate_revenue(catalog, MAX_BOOKS));
36     
37     return 0;
38 }
39 
40 // 書籍情報の表示関数
41 void display_books(Publication books[], int size) {
42     printf("%-20s %-30s %-20s %-15s %-10s\n",
43         "ID", "タイトル", "著者", "価格", "数量");
44     for (int i = 0; i < size; i++) {
45         printf("%-20s %-30s %-20s %-15.2f %-10d\n",
46             books[i].book_id, books[i].title, books[i].writer, 
47             books[i].price, books[i].quantity);
48     }
49 }
50 
51 // 売上数量でソートする関数
52 void arrange_by_quantity(Publication books[], int size) {
53     for (int i = 0; i < size - 1; i++) {
54         int max_idx = i;
55         for (int j = i + 1; j < size; j++) {
56             if (books[j].quantity > books[max_idx].quantity) {
57                 max_idx = j;
58             }
59         }
60         if (max_idx != i) {
61             Publication temp = books[i];
62             books[i] = books[max_idx];
63             books[max_idx] = temp;
64         }
65     }
66 }
67 
68 // 総売上高を計算する関数
69 double calculate_revenue(Publication books[], int size) {
70     double total = 0;
71     for (int i = 0; i < size; i++) {
72         total += books[i].price * books[i].quantity;
73     }
74     return total;
75 }

課題45、演習課題5

date_operations.cソースコードと実行結果:

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <stdio.h>
 3 
 4 typedef struct {
 5     int year;
 6     int month;
 7     int day;
 8 } CalendarDate;
 9 
10 // 関数宣言
11 void enter_date(CalendarDate *date_ptr);               // 日付を入力
12 int day_number(CalendarDate date);                    // その年の何日目かを返す
13 int compare_dates(CalendarDate d1, CalendarDate d2);  // 2つの日付を比較
14 
15 void test_day_count() {
16     CalendarDate input_date;
17     int counter;
18 
19     printf("日付を入力 (例: 2025-06-01):\n");
20     for(counter = 0; counter < 3; ++counter) {
21         enter_date(&input_date);
22         printf("%d-%02d-%02d は %d 年の %d 日目です\n\n", 
23                input_date.year, input_date.month, input_date.day, 
24                input_date.year, day_number(input_date));
25     }
26 }
27 
28 void test_date_comparison() {
29     CalendarDate person1, person2;
30     int counter;
31     int result;
32 
33     printf("2人の誕生日を入力 (例: 2025-06-01):\n");
34     for(counter = 0; counter < 3; ++counter) {
35         enter_date(&person1);
36         enter_date(&person2);
37         result = compare_dates(person1, person2);
38         
39         if(result == 0)
40             printf("2人は同じ年齢です\n\n");
41         else if(result == -1)
42             printf("1人目の方が年上です\n\n");
43         else
44             printf("1人目の方が年下です\n\n");
45     }
46 }
47 
48 int main() {
49     printf("テスト1: 日付を入力し、その年の何日目かを表示\n");
50     test_day_count();
51 
52     printf("\nテスト2: 2人の年齢比較\n");
53     test_date_comparison();
54 }
55 
56 // 日付入力関数
57 void enter_date(CalendarDate *date_ptr) {
58     scanf("%d-%d-%d", &date_ptr->year, &date_ptr->month, &date_ptr->day);
59 }
60 
61 // その年の何日目かを計算
62 int day_number(CalendarDate date) {
63     int days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
64     int day_count = 0;
65     
66     // うるう年の判定
67     if ((date.year % 4 == 0 && date.year % 100 != 0) || date.year % 400 == 0) {
68         days_in_month[1] = 29;
69     }
70     
71     for (int i = 0; i < date.month - 1; i++) {
72         day_count += days_in_month[i];
73     }
74     day_count += date.day;
75     return day_count;
76 }
77 
78 // 2つの日付を比較
79 int compare_dates(CalendarDate d1, CalendarDate d2) {
80     // 年の比較
81     if (d1.year != d2.year) {
82         return (d1.year < d2.year) ? -1 : 1;
83     }
84     
85     // 月の比較
86     if (d1.month != d2.month) {
87         return (d1.month < d2.month) ? -1 : 1;
88     }
89     
90     // 日の比較
91     if (d1.day != d2.day) {
92         return (d1.day < d2.day) ? -1 : 1;
93     }
94     
95     return 0; // 同じ日付
96 }

課題56、演習課題6

account_manager.cソースコードと実行結果:

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 enum UserType {administrator, pupil, educator};
 5 
 6 typedef struct {
 7     char login_id[20];   // ログインID
 8     char passcode[20];   // パスワード
 9     enum UserType role;  // ユーザータイプ
10 } UserAccount;
11 
12 
13 // 関数宣言
14 void print_accounts(UserAccount accounts[], int count);  // アカウント情報を表示(パスワードは*表示)
15 
16 int main() {
17     UserAccount accounts[] = {
18         {"A1001", "123456", pupil},
19         {"A1002", "123abcdef", pupil},
20         {"A1009", "xyz12121", pupil}, 
21         {"X1009", "9213071x", administrator},
22         {"C11553", "129dfg32k", educator},
23         {"X3005", "921kfmg917", pupil}
24     };
25     int account_count;
26     account_count = sizeof(accounts)/sizeof(UserAccount);
27     print_accounts(accounts, account_count);
28 
29     return 0;
30 }
31 
32 // アカウント情報を表示する関数
33 void print_accounts(UserAccount accounts[], int count) {
34     for (int i = 0; i < count; i++) {
35         int pass_len = strlen(accounts[i].passcode);
36         const char* user_type_str;
37         
38         // ユーザータイプに応じた文字列を設定
39         switch (accounts[i].role) {
40         case administrator: 
41             user_type_str = "管理者"; 
42             break;
43         case pupil: 
44             user_type_str = "学生"; 
45             break;
46         case educator: 
47             user_type_str = "教師"; 
48             break;
49         default: 
50             user_type_str = "不明"; 
51             break;
52         }
53         
54         printf("%-8s ", accounts[i].login_id);
55         
56         // パスワードを*で表示
57         for (int j = 0; j < pass_len; j++)
58             printf("*");
59             
60         // 表示を揃えるためのスペース
61         for (int j = pass_len; j < 12; j++)
62             printf(" ");
63             
64         printf(" %-8s\n", user_type_str);
65     }
66 }

課題67、演習課題7

contact_system.cソースコードと実行結果:

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 typedef struct {
 6     char full_name[20];   // 氏名
 7     char mobile[12];      // 電話番号
 8     int  priority;        // 優先度(1: 高, 0: 通常)
 9 } PersonInfo; 
10 
11 
12 // 関数宣言
13 void mark_priority(PersonInfo contacts[], int total, char name[]);  // 優先連絡先を設定
14 void show_all(PersonInfo contacts[], int total);    // 全連絡先を表示
15 void display_sorted(PersonInfo contacts[], int total);   // 氏名順に表示(優先先頭)
16 
17 
18 #define CONTACTS_SIZE 10
19 int main() {
20     PersonInfo contact_list[CONTACTS_SIZE] = {
21         {"刘一", "15510846604", 0},
22         {"陈二", "18038747351", 0},
23         {"张三", "18853253914", 0},
24         {"李四", "13230584477", 0},
25         {"王五", "15547571923", 0},
26         {"赵六", "18856659351", 0},
27         {"周七", "17705843215", 0},
28         {"孙八", "15552933732", 0},
29         {"吴九", "18077702405", 0},
30         {"郑十", "18820725036", 0}
31     };
32     
33     int priority_count, index;
34     char search_name[20];
35 
36     printf("連絡先リスト(初期状態): \n"); 
37     show_all(contact_list, CONTACTS_SIZE);
38 
39     printf("\n優先連絡先の人数を入力: ");
40     scanf("%d", &priority_count);
41     
42     printf("%d人の優先連絡先の氏名を入力:\n", priority_count);
43     for(index = 0; index < priority_count; ++index) {
44         scanf("%s", search_name);
45         mark_priority(contact_list, CONTACTS_SIZE, search_name);
46     }
47 
48     printf("\n連絡先リスト(氏名順、優先先頭):\n");
49     display_sorted(contact_list, CONTACTS_SIZE);
50 
51     return 0;
52 }
53 
54 // 優先連絡先を設定する関数
55 void mark_priority(PersonInfo contacts[], int total, char name[]) {
56     for (int i = 0; i < total; i++) {
57         if (strcmp(contacts[i].full_name, name) == 0) {
58             contacts[i].priority = 1;
59             return;
60         }
61     }
62 }
63 
64 // 氏名順に表示する関数(優先先頭)
65 void display_sorted(PersonInfo contacts[], int total) {
66     PersonInfo sorted_list[CONTACTS_SIZE];
67     memcpy(sorted_list, contacts, sizeof(PersonInfo) * total);
68     
69     // 優先度でソート
70     for (int i = 0; i < total - 1; i++) {
71         for (int j = 0; j < total - i - 1; j++) {
72             // 優先度で比較
73             if (sorted_list[j].priority < sorted_list[j + 1].priority) {
74                 PersonInfo temp = sorted_list[j];
75                 sorted_list[j] = sorted_list[j + 1];
76                 sorted_list[j + 1] = temp;
77             }
78             // 同じ優先度なら氏名で比較
79             else if (sorted_list[j].priority == sorted_list[j + 1].priority && 
79                      strcmp(sorted_list[j].full_name, sorted_list[j + 1].full_name) > 0) {
80                 PersonInfo temp = sorted_list[j];
81                 sorted_list[j] = sorted_list[j + 1];
82                 sorted_list[j + 1] = temp;
83             }
84         }
85     }
86     show_all(sorted_list, total);
87 }
88 
89 // 連絡先情報を表示する関数
90 void show_all(PersonInfo contacts[], int total) {
91     for(int i = 0; i < total; ++i) {
92         printf("%-10s%-15s", contacts[i].full_name, contacts[i].mobile);
93         if(contacts[i].priority)
94             printf("%5s", "*");
95         printf("\n");
96     }
97 }

課題7

タグ: C言語 構造体 アルゴリズム ソート データ構造

7月16日 20:01 投稿