輸入n,判斷幾個乘客請求,輸入第n個請求,創建一個電梯狀態的結構體,包含電梯的層數,當前層,當前時間,目的信息,按時間順序輸入請求更新電梯目的信息,電梯當有目的爲完成時繼續向目的移動,到目標樓層後刪除請求並彈出當前樓層和當前時間做爲輸出,處理完全部請求後程序結束安全
C語言是把電梯的操做拆開成各個分開的函數和對變量的刪改,按照求解的順序調用函數得出答案函數
C++面向對象則是把電梯抽象成類,各類函數和變量被封裝在類中,結構更加優美,擴展性好,並且命名在類內容易識別不易衝突,公有私有成員提升了程序的安全性。code
#pragma once class elevator_new { public: elevator_new(int n,int k=0); ~elevator_new(); int ask_floor(); int ask_for_state(); int update_state(int floor);//到達某一層標記 int downdate_state(int floor);//清除到達某一層標記 void run(); private: void get(int people); void out(int people); void MoveUp(); void MoveDowm(); int aim[50];//電梯運行的目的標記樓層 int state;//電梯運行狀態 1空載2有客 int people_num;//電梯內乘客數量 int elevator_place;//電梯當前位置 int timer;//電梯當前時間 };
#include "elevator_new.h" elevator_new::elevator_new(int n,int k=0)//一個有n個連續目的樓層的電梯,起始樓層k; { state = 1;//empty for (int i = 0; i <= n; i++) { aim[i] = 0; } elevator_place = k; } elevator_new::~elevator_new() { } void elevator_new::MoveDowm() { elevator_place--; } void elevator_new::MoveUp() { elevator_place++; } void elevator_new::get(int people) { people_num += people; } void elevator_new::out(int people) { people_num -= people; } int elevator_new::ask_floor() { return elevator_place; } int elevator_new::ask_for_state() { return state; } int elevator_new::update_state(int floor) { if (floor == -1) { state = 1; return 0; } else { state = 2; aim[floor] = 1; return 1; } } int elevator_new::downdate_state(int floor) { aim[floor] = 0; bool k = 0; for (int i = 0; i <= 10; i++) { if (aim[i] == 1) k = 1; } if (k == 0) state = 1; return 1; } int elevator_new::run() { }
`對象