C++有限狀態(tài)機實現(xiàn)計算器小程序
本文介紹利用有限狀態(tài)機原理開發(fā)計算器小程序的過程。
實現(xiàn)的功能
- 支持整數(shù)、小數(shù)輸入
- 支持+ - * / 四則運算
- CE 清除當前操作數(shù)
- C 清除所有、回到初始狀態(tài)
- 回顯操作數(shù)和結(jié)果
HSM狀態(tài)圖
計算器可以分為七種狀態(tài):Start、Operand_1、Negate_1、Operator、Operand_2、Negate_2、Error。其中Start、Operand_1、Operand_1狀態(tài)又分了幾種子狀態(tài)。 下面簡要的介紹下狀態(tài)狀態(tài)轉(zhuǎn)換的過程:
- 啟動軟件,進入Start狀態(tài)
- 當用戶點擊1-9、0、Point按鈕,軟件進入Operand_1 狀態(tài)。
- 當用戶點擊+、-、*、/按鈕,軟件進入Operator狀態(tài)。
- 此時當用戶再次點擊1-9、0、Point按鈕,軟件進入Operand_2 狀態(tài)。
- 如果用戶點擊=按鈕,軟件就進入了Start狀態(tài)。
- 如果此時進行的是除法運算且除數(shù)為0,軟件進入Error狀態(tài),用戶只有點擊C按鈕才可以跳出。
在實際開發(fā)的過程中,我們只需要關(guān)心現(xiàn)在程序處在什么狀態(tài),可以進行什么樣的操作。然后就是狀態(tài)轉(zhuǎn)換的條件要處理下。
代碼片段
下面是CalculatorDlg.cpp中的一段代碼,我們首先要獲得當前的狀態(tài),然后進行相應的操作,操作完成之后設置好對應的狀態(tài)。
void CalculatorDlg::enterOperation(Calculator::CalcOp oper) { if (m_calculator.getCurrentState() == Calculator::CalcState::Error) { return; } if (m_calculator.getCurrentState() == Calculator::CalcState::Start || m_calculator.getCurrentState() == Calculator::CalcState::Negate_1 || m_calculator.getCurrentState() == Calculator::CalcState::Operand_1) { m_calculator.setOperand_1(_wtof(m_output)); } else if (m_calculator.getCurrentState() == Calculator::CalcState::Operand_2 || m_calculator.getCurrentState() == Calculator::CalcState::Negate_2) { m_calculator.setOperand_2(_wtof(m_output)); UpdateData(TRUE); std::stringstream ss; ss << m_calculator.getResult(); m_output = ss.str().c_str(); UpdateData(FALSE); m_calculator.setCurrentState(Calculator::CalcState::Start); m_calculator.setOperand_1(m_calculator.getResult()); } m_calculator.setCurrentState(Calculator::CalcState::Operator); m_calculator.setOperator(oper); }
運行效果展示
源碼查看
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++/Php/Python 語言執(zhí)行shell命令的方法(推薦)
下面小編就為大家?guī)硪黄狢++/Php/Python 語言執(zhí)行shell命令的方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03C++實現(xiàn)LeetCode(兩個有序數(shù)組的中位數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(兩個有序數(shù)組的中位數(shù)),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07