作者:李君威U201310747
状态机图示:
将起落杆的位置状态和通行灯信号作为两个类对象,汽车出入闸传感器信号作为输入,编写代码:
1 // qichemenjin.cpp 2 //Copy right by Justin. 3 4 #include "stdafx.h" 5 #include <iostream> 6 using namespace std; 7 class Liftlever 8 { 9 public: 10 bool Leverstate; //起落杆位置 11 void Changeleverstate() 12 { 13 Leverstate = !Leverstate; 14 }; 15 }; 16 17 class Light 18 { 19 public: 20 bool Lightstate; //通行灯信号 21 void Changelightstate() 22 { 23 Lightstate = !Lightstate; 24 }; 25 }; 26 27 void showleverstate(bool state) 28 { 29 if(state==true) 30 cout << "起落杆升起" << endl; 31 else 32 cout << "起落杆落下" << endl; 33 }; 34 35 void showlightstate(bool state) 36 { 37 if (state == true) 38 cout << "绿灯亮" << endl; 39 else 40 cout << "红灯亮" << endl; 41 }; 42 43 Liftlever Liftleverdemo; 44 Light Lightdemo; 45 46 bool Controlsystem(char car) 47 { 48 switch (car) 49 { 50 case ‘y‘: 51 Liftleverdemo.Changeleverstate(); 52 break; 53 case ‘n‘: 54 break; 55 }; 56 57 showleverstate(Liftleverdemo.Leverstate); 58 59 switch (Liftleverdemo.Leverstate) 60 { 61 case true: 62 Lightdemo.Lightstate = true; 63 cout << "绿灯亮" << endl; 64 break; 65 case false: 66 Lightdemo.Lightstate = false; 67 cout << "红灯亮" << endl<<endl; 68 break; 69 }; 70 return Lightdemo.Lightstate; 71 }; 72 73 74 int main() 75 { 76 char carin; 77 char carout; 78 while (1) 79 { 80 cout << "是否有车辆进入?(y/n)" << endl; 81 cin >> carin; 82 bool nextstep = Controlsystem(carin); 83 while (nextstep) 84 { 85 cout << "车辆是否已经驶出?(y/n)" << endl; 86 cin >> carout; 87 nextstep = Controlsystem(carout); 88 }; 89 }; 90 return 0; 91 }
运行结果:
时间: 2024-10-18 08:19:11