#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义车次结构体
typedef struct {
char trainNumber[10];
int totalSeats;
int availableSeats;
} Train;
// 显示菜单
void showMenu() {
printf(“1. 查看车次信息\n”);
printf(“2. 订票\n”);
printf(“3. 退票\n”);
printf(“4. 退出\n”);
}
// 查看车次信息
void viewTrains(Train *trains, int numTrains) {
printf(“车次信息列表:\n”);
for (int i = 0; i < numTrains; i++) {
printf("%d. 车次: %s - 总座位数: %d - 剩余座位数: %d\n", i + 1, trains[i].trainNumber, trains[i].totalSeats, trains[i].availableSeats);
}
}
// 订票
void bookTicket(Train *trains, int numTrains) {
char trainNumber[10];
printf(“请输入要订票的车次: “);
scanf(”%s”, trainNumber);
int found = 0;
for (int i = 0; i < numTrains; i++) {
if (strcmp(trains[i].trainNumber, trainNumber) == 0 && trains[i].availableSeats > 0) {
trains[i].availableSeats--;
printf("订票成功!\n");
found = 1;
break;
}
}
if (!found || trains[i].availableSeats == 0) {
printf("订票失败,车次不存在或无剩余座位!\n");
}
}
// 退票
void cancelTicket(Train *trains, int numTrains) {
char trainNumber[10];
printf(“请输入要退票的车次: “);
scanf(”%s”, trainNumber);
int found = 0;
for (int i = 0; i < numTrains; i++) {
if (strcmp(trains[i].trainNumber, trainNumber) == 0) {
trains[i].availableSeats++;
printf("退票成功!\n");
found = 1;
break;
}
}
if (!found) {
printf("退票失败,车次不存在!\n");
}
}
int main() {
Train trains[5] = {
{“T001”, 100, 50},
{“T002”, 80, 30},
{“T003”, 120, 60},
{“T004”, 90, 40},
{“T005”, 110, 55}
};
int numTrains = 5;
int choice;
do {
showMenu();
printf("请选择操作: ");
scanf("%d", &choice);
switch (choice) {
case 1:
viewTrains(trains, numTrains);
break;
case 2:
bookTicket(trains, numTrains);
break;
case 3:
cancelTicket(trains, numTrains);
break;
case 4:
printf("退出程序\n");
break;
default:
printf("无效的选择,请重新输入\n");
}
} while (choice!= 4);
return 0;
}