首页 > 代码库 > 用C++模拟电梯运行

用C++模拟电梯运行

首先假设有6个楼层。最初,电梯在顶层,先实现电梯从顶层到第一层的过程:

#include <iostream>#include<stdio.h>
#include<string.h>
#include<time.h>
#include<stdlib.h>
#include<windows.h>
using namespace std;


struct node{int x,y;int color;};
HANDLE Output=GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE Input=GetStdHandle(STD_INPUT_HANDLE);
void SetCursor(int x,int y){
COORD cd={x,y};
SetConsoleCursorPosition(Output,cd);
}
int main()
{
int floor = 6;
for(int i=1; i<17; i++)
{
if( i%3 == 1)
{
SetCursor(1,i);
cout << floor;
floor--;
}

}
bool bot = true;
int position = 1;
while(bot)
{
SetCursor(3,position);
cout << "■" << endl;
Sleep(500);
SetCursor(3,position);
cout << " " << endl;
if(position == 16)
{
bot = false;
SetCursor(3,position);
cout << "■" << endl;
}
position++;
}
//cout << "■" << endl;
return 0;
}

 

这时还没有加入人。

下面实现单人电梯模型,人和电梯在的楼层都是随机的,人想到达的楼层也是随机的。

单人电梯模型:

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<time.h>
#include<stdlib.h>
#include<windows.h>
#include <cstdlib>
using namespace std;


struct node{int x,y;int color;};
HANDLE Output=GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE Input=GetStdHandle(STD_INPUT_HANDLE);
void SetCursor(int x,int y){
COORD cd={x,y};
SetConsoleCursorPosition(Output,cd);
}
int main()
{
int floor = 6;
for(int i=1; i<17; i++)
{
if( i%3 == 1)
{
SetCursor(1,i);
cout << floor;
floor--;
}

}
srand(time(0));
int prompt = 17;
const int nort = 500;
const int slowt = 1000;
int elevator = (rand()%6) + 1;
int perx = (rand()%6) + 1;
int pery = (rand()%6) + 1;
while(perx == pery)
{
int perx = (rand()%6) + 1;
int pery = (rand()%6) + 1;
}
int position = 19 - 3*elevator;
int elex = 19 - 3*perx;
int eley = 19 - 3*pery;
bool reachx = false;
bool reachy = false;
int state = 0;
SetCursor(3,prompt);
cout << "elevator is on " << elevator << " floor";
prompt++;
SetCursor(3,prompt);
cout << perx << " floor wants to go to " << pery << " floor";
prompt++;
while(!reachx)
{
if(position < elex)
state = 1;
else
state = 2;
SetCursor(3,position);
cout << "■" << endl;
Sleep(nort);
SetCursor(3,position);
cout << " " << endl;
if(state == 1)
position++;
else
position--;
if(position == elex)
{
reachx = true;
SetCursor(3,position);
cout << "■" << endl;
Sleep(slowt);
SetCursor(3,position);
cout << " " << endl;
}
}
SetCursor(3,prompt);
cout << "has reached " << perx << " floor";
prompt++;
while(!reachy)
{
if(position < eley)
state = 1;
else
state = 2;
SetCursor(3,position);
cout << "■" << endl;
Sleep(nort);
SetCursor(3,position);
cout << " " << endl;
if(state == 1)
position++;
else
position--;
if(position == eley)
{
reachy = true;
SetCursor(3,position);
cout << "■" << endl;
}
}
SetCursor(3,prompt);
cout << "has reached " << pery << " floor";
prompt++;
SetCursor(1,20);
return 0;
}

用C++模拟电梯运行