写一个火车购票的c++程序
时间: 2024-03-15 16:46:21 浏览: 10
以下是一个简单的火车购票的C++程序:
```
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int seats[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int choice = 0;
int tickets = 0;
int total_tickets = 0;
double price = 0.0;
double total_price = 0.0;
cout << "Welcome to Train Ticket Booking System!" << endl;
cout << "======================================" << endl;
while (true) {
cout << "Available seats: ";
for (int i = 0; i < 10; i++) {
if (seats[i] == 1) {
cout << i+1 << " ";
}
}
cout << endl;
cout << "Please choose a seat (1-10): ";
cin >> choice;
if (choice < 1 || choice > 10) {
cout << "Invalid choice. Please try again." << endl;
continue;
}
if (seats[choice-1] == 0) {
cout << "Sorry, this seat is already booked. Please choose another seat." << endl;
continue;
}
cout << "How many tickets would you like to book? ";
cin >> tickets;
if (tickets < 1) {
cout << "Invalid number of tickets. Please try again." << endl;
continue;
}
price = 50.0 * tickets;
total_price += price;
total_tickets += tickets;
cout << "You have booked " << tickets << " ticket(s) for seat " << choice << "." << endl;
cout << "The total price for this booking is $" << fixed << setprecision(2) << price << "." << endl;
cout << "The total number of tickets booked is " << total_tickets << "." << endl;
cout << "The total price for all bookings is $" << fixed << setprecision(2) << total_price << "." << endl;
seats[choice-1] = 0;
cout << "Thank you for using Train Ticket Booking System!" << endl;
cout << "===============================================" << endl;
}
return 0;
}
```
这个程序使用一个名为 `seats` 的整数数组来记录每个座位的预订状态,0表示已被预订,1表示可用。每次循环迭代时,程序首先显示所有可用的座位,并要求用户选择一个座位。然后它要求用户输入要预订的票数,并计算总价。最后,它更新 `seats` 数组,将所选座位标记为已预订,并显示一些有关预订的信息。该程序使用一个无限循环,直到用户选择退出。