航班订票系统,查询航班信息,订票,退票,C语言代码
时间: 2023-08-18 17:41:32 浏览: 43
以下是一个简单的航班订票系统的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FLIGHTS 10
#define MAX_NAME_LENGTH 30
typedef struct {
char from[MAX_NAME_LENGTH];
char to[MAX_NAME_LENGTH];
int seats;
int price;
} Flight;
Flight flights[MAX_FLIGHTS];
int num_flights = 0;
void add_flight(char *from, char *to, int seats, int price) {
if (num_flights >= MAX_FLIGHTS) {
printf("Sorry, the maximum number of flights has been reached.\n");
return;
}
Flight new_flight;
strcpy(new_flight.from, from);
strcpy(new_flight.to, to);
new_flight.seats = seats;
new_flight.price = price;
flights[num_flights++] = new_flight;
printf("Flight added successfully.\n");
}
void print_flights() {
printf("Flights:\n");
for (int i = 0; i < num_flights; i++) {
printf("%d. %s to %s, %d seats available, price: %d\n",
i + 1, flights[i].from, flights[i].to, flights[i].seats, flights[i].price);
}
}
int find_flight(char *from, char *to) {
for (int i = 0; i < num_flights; i++) {
if (strcmp(flights[i].from, from) == 0 && strcmp(flights[i].to, to) == 0) {
return i;
}
}
return -1;
}
void book_flight(char *from, char *to, int num_passengers) {
int index = find_flight(from, to);
if (index == -1) {
printf("Sorry, no flights available from %s to %s.\n", from, to);
return;
}
Flight *flight = &flights[index];
if (flight->seats < num_passengers) {
printf("Sorry, only %d seats available on the %s to %s flight.\n",
flight->seats, flight->from, flight->to);
return;
}
flight->seats -= num_passengers;
printf("Successfully booked %d seats on the %s to %s flight.\n",
num_passengers, flight->from, flight->to);
}
void cancel_flight(char *from, char *to, int num_passengers) {
int index = find_flight(from, to);
if (index == -1) {
printf("Sorry, no flights available from %s to %s.\n", from, to);
return;
}
Flight *flight = &flights[index];
flight->seats += num_passengers;
printf("Successfully cancelled %d seats on the %s to %s flight.\n",
num_passengers, flight->from, flight->to);
}
int main() {
add_flight("New York", "Los Angeles", 50, 500);
add_flight("Los Angeles", "Chicago", 40, 400);
add_flight("New York", "Chicago", 30, 450);
print_flights();
book_flight("New York", "Los Angeles", 2);
book_flight("Los Angeles", "Chicago", 4);
book_flight("New York", "Chicago", 3);
cancel_flight("New York", "Los Angeles", 1);
print_flights();
return 0;
}
```
该代码定义了一个 `Flight` 结构体,其中包含航班的起始地点,目的地,可用座位数,价格等信息。 `add_flight` 函数用于添加新的航班, `print_flights` 函数用于打印所有可用的航班, `find_flight` 函数用于查找给定起始地点和目的地的航班, `book_flight` 函数用于预订航班, `cancel_flight` 函数用于取消预订。在 `main` 函数中,我们先添加了三个航班,然后对它们进行了一些操作,最后打印出所有可用的航班。