C语言设计一个实现预约座位的函数
时间: 2023-05-28 11:05:21 浏览: 51
以下是一个简单的实现预约座位的函数的示例:
```c
#include <stdio.h>
// 定义座位数量
#define SEATS 10
// 定义座位状态
#define AVAILABLE 0
#define RESERVED 1
// 定义座位数组
int seatStatus[SEATS];
// 函数声明
void printSeatStatus();
int reserveSeat(int seatNumber);
int main() {
int seatNumber, result;
char choice;
// 初始化座位状态
for (int i = 0; i < SEATS; i++) {
seatStatus[i] = AVAILABLE;
}
do {
// 打印座位状态
printf("\nCurrent seat status:\n");
printSeatStatus();
// 询问座位号
printf("\nEnter seat number to reserve: ");
scanf("%d", &seatNumber);
// 预约座位
result = reserveSeat(seatNumber);
// 根据结果输出提示信息
if (result == -1) {
printf("Invalid seat number. Please try again.\n");
} else if (result == 0) {
printf("Sorry, seat %d has already been reserved. Please choose another seat.\n", seatNumber);
} else {
printf("Seat %d has been reserved successfully.\n", seatNumber);
}
// 询问是否继续预约
printf("\nDo you want to reserve another seat? (y/n): ");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
// 打印座位状态
void printSeatStatus() {
for (int i = 0; i < SEATS; i++) {
printf("%d ", seatStatus[i]);
}
printf("\n");
}
// 预约座位
int reserveSeat(int seatNumber) {
// 检查座位号是否有效
if (seatNumber < 1 || seatNumber > SEATS) {
return -1;
}
// 检查座位是否已被预约
if (seatStatus[seatNumber - 1] == RESERVED) {
return 0;
}
// 预约座位
seatStatus[seatNumber - 1] = RESERVED;
return 1;
}
```
在这个示例中,我们首先定义了座位数量和座位状态的常量,并声明了打印座位状态和预约座位的函数。
在 `main()` 函数中,我们首先初始化座位状态数组,然后进入一个循环,每次循环中打印当前的座位状态,询问用户要预约哪个座位,调用预约座位的函数进行预约,并根据预约结果输出相应的提示信息。在循环结束前,我们还会询问用户是否继续预约。
在 `printSeatStatus()` 函数中,我们简单地遍历座位状态数组并打印每个元素的值。
在 `reserveSeat()` 函数中,我们首先检查座位号是否有效,如果无效则返回 `-1`。然后检查座位是否已被预约,如果已被预约则返回 `0`。最后,如果座位可用,则将座位状态设置为已预约,并返回 `1`。
请注意,这个示例是一个简单的实现,实际应用中可能需要更多的功能,例如取消预约、查询座位状态等。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)