用c语言写个火车票订票系统
时间: 2023-11-22 18:53:51 浏览: 266
C语言项目——火车订票系统.zip
5星 · 资源好评率100%
好的,下面是一个简单的火车票订票系统的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TRAIN_NUM 100
#define MAX_SEAT_NUM 100
struct Train {
char name[50];
int seats[MAX_SEAT_NUM];
};
struct Train trains[MAX_TRAIN_NUM];
int trainNum = 0;
void addTrain(char* name, int* seats, int seatNum) {
if (trainNum >= MAX_TRAIN_NUM) {
printf("The maximum number of trains has been reached.\n");
return;
}
struct Train train;
strcpy(train.name, name);
for (int i = 0; i < seatNum; i++) {
train.seats[i] = seats[i];
}
trains[trainNum] = train;
trainNum++;
printf("Train added successfully.\n");
}
void bookTicket(int trainIndex, int seatNum) {
if (trainIndex < 0 || trainIndex >= trainNum) {
printf("Invalid train index.\n");
return;
}
struct Train train = trains[trainIndex];
if (seatNum < 0 || seatNum >= MAX_SEAT_NUM) {
printf("Invalid seat number.\n");
return;
}
if (train.seats[seatNum] == 0) {
printf("The seat is already booked.\n");
return;
}
train.seats[seatNum] = 0;
trains[trainIndex] = train;
printf("Ticket booked successfully.\n");
}
void showTrainInfo(int trainIndex) {
if (trainIndex < 0 || trainIndex >= trainNum) {
printf("Invalid train index.\n");
return;
}
struct Train train = trains[trainIndex];
printf("Train Name: %s\n", train.name);
printf("Total Seats: %d\n", sizeof(train.seats) / sizeof(int));
printf("Available Seats:\n");
for (int i = 0; i < sizeof(train.seats) / sizeof(int); i++) {
if (train.seats[i] != 0) {
printf("%d ", i+1);
}
}
printf("\n");
}
void showAllTrains() {
printf("Total Trains: %d\n", trainNum);
printf("Train List:\n");
for (int i = 0; i < trainNum; i++) {
printf("%d. %s\n", i+1, trains[i].name);
}
}
int main() {
int choice;
do {
printf("\nWelcome to Train Ticket Booking System\n");
printf("1. Add Train\n");
printf("2. Book Ticket\n");
printf("3. Show Train Info\n");
printf("4. Show All Trains\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: {
char name[50];
int seatNum;
printf("Enter train name: ");
scanf("%s", name);
printf("Enter number of seats: ");
scanf("%d", &seatNum);
int seats[MAX_SEAT_NUM];
for (int i = 0; i < seatNum; i++) {
seats[i] = i + 1;
}
addTrain(name, seats, seatNum);
break;
}
case 2: {
int trainIndex, seatNum;
printf("Enter train index: ");
scanf("%d", &trainIndex);
printf("Enter seat number: ");
scanf("%d", &seatNum);
bookTicket(trainIndex - 1, seatNum - 1);
break;
}
case 3: {
int trainIndex;
printf("Enter train index: ");
scanf("%d", &trainIndex);
showTrainInfo(trainIndex - 1);
break;
}
case 4: {
showAllTrains();
break;
}
case 5: {
exit(0);
}
default: {
printf("Invalid choice.\n");
break;
}
}
} while (1);
return 0;
}
```
这个程序中,我们定义了一个结构体 `Train`,其中包含火车名称和座位数组。然后我们使用数组来存储火车信息,可以添加火车、订票、查看火车信息和列出所有火车的列表。
阅读全文