C++模拟十字路口并且添加15秒的红绿灯,车的数量不能超过50
时间: 2023-07-15 12:12:10 浏览: 13
以下是一个简单的C++代码,模拟了一个十字路口和15秒的红绿灯。它使用了一个循环来模拟不断到来的车辆,并且使用了计数器来限制车辆数量。
```
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
int main() {
int max_cars = 50; // 最大车辆数
int cars = 0; // 当前车辆数
bool light = false; // 红绿灯状态,false为红灯,true为绿灯
while (true) {
// 模拟车辆到达
if (cars < max_cars) {
cout << "车辆到达" << endl;
cars++;
}
// 红绿灯倒计时
for (int i = 15; i > 0; i--) {
cout << "红绿灯倒计时:" << i << endl;
this_thread::sleep_for(chrono::seconds(1));
}
// 切换红绿灯状态
light = !light;
if (light) {
cout << "绿灯亮起,可通行" << endl;
} else {
cout << "红灯亮起,禁止通行" << endl;
}
// 重置车辆数量
cars = 0;
}
return 0;
}
```
请注意,这只是一个简单的示例代码,没有考虑到许多实际情况,如车辆的速度、转弯等。如果您需要更精细的模拟,请考虑使用更高级的模拟工具或框架。
相关推荐
















