编写一个座位预定程序需要考虑以下几个关键点:
数据结构:
定义一个合适的数据结构来存储座位信息,如编号、是否被预定、预定人姓名等。
用户界面:
提供一个用户友好的界面,让用户可以方便地选择座位和查看预定状态。
逻辑处理:
实现座位的查找、预定、取消预定等逻辑功能。
数据持久化:
如果需要保存预定信息,需要将数据保存到数据库或其他存储介质中。
```c
include include include define MAX_SEATS 100 define MAX_NAME 50 typedef struct { int num; char name[MAX_NAME]; int flag; // 0: 未预定, 1: 已预定 } Seat; Seat seats[MAX_SEATS]; int seat_count = 0; void initialize_seats() { memset(seats, 0, sizeof(seats)); seat_count = 0; } void display_seats() { for (int i = 0; i < seat_count; i++) { printf(" %d. %s ", i + 1, seats[i].name); } printf("\n"); } int find_empty_seat() { for (int i = 0; i < seat_count; i++) { if (seats[i].flag == 0) { return i; } } return -1; } void reserve_seat(int index) { if (index >= 0 && index < seat_count) { seats[index].flag = 1; printf("座位 %d 已成功预定。\n", index + 1); } else { printf("无效的座位编号。\n"); } } void cancel_seat(int index) { if (index >= 0 && index < seat_count) { seats[index].flag = 0; printf("座位 %d 已取消预定。\n", index + 1); } else { printf("无效的座位编号。\n"); } } int main() { int choice; char name[MAX_NAME]; initialize_seats(); while (1) { printf("1. 显示空座位\n"); printf("2. 预定座位\n"); printf("3. 取消预定\n"); printf("4. 退出\n"); printf("请输入您的选择: "); scanf("%d", &choice); switch (choice) { case 1: display_seats(); break; case 2: printf("请输入您的姓名: "); scanf("%s", name); printf("请输入要预定的座位编号: "); int seat_index = find_empty_seat(); if (seat_index != -1) { reserve_seat(seat_index); } break; case 3: printf("请输入要取消预定的座位编号: "); scanf("%d", &seat_index); cancel_seat(seat_index); break; case 4: printf("感谢使用,再见!\n"); return 0; default: printf("无效的选择,请重新输入。\n"); } } return 0; } ``` 代码说明: 使用`Seat`结构体来存储座位信息,包括编号、姓名和预定状态。 `initialize_seats`函数用于初始化所有座位为未预定状态。 `display_seats`函数用于显示所有空座位的编号。 `find_empty_seat`函数用于查找第一个未预定的座位。 `reserve_seat`函数用于预定指定编号的座位。 `cancel_seat`函数用于取消指定编号的座位预定。 `main`函数提供用户数据结构:
初始化座位:
显示座位:
查找空座位:
预定座位:
取消预定:
主函数: