Example of simple calculator using a stack (Calculator)

xiaoxiao2021-03-06  102

/ * Calculator.h * / # iFNDef __calculator_h __ # define __calculator_h__

#include #include "stack.h"

Class Calculator {private: // Stack Stack S; // Press a Double Operation to Void Enter (Double Operand) {s.push (Operand);} // From the top of the stack Read two operands INT GETTWOOPERANDS (Double & Operand1, Double & Operand2) {if (s.stackempty ()) {cerr << "No Operand to Pop! << endl; s.clearstack (); return 0;} Operand1 = S.POP (); if (S.StackeMpty ()) {CERR << "No Operand to Pop! << Endl; s.clearstack (); return 0;} OPERAND2 = S.POP (); Return 1 } // The two operands read by getting GetTWoOperands are calculated OP void compute (char OP) {Double Operand1, Operand2, Result; if (! Gettwooperands (Operand1, Operand2)) Return; Switch (OP) {CASE ' ': Result = OPERAND1 OPERAND2; BREAK; CASE' - ': Result = OPERAND1 - OPERAND2; BREAK; CASE' * ': Result = OPERAND1 * OPERAND2; BREAK; CASE' / ': IF (OPERAND2 == 0) {CERR << "Divided by 0!" << endl; s.clearstack (); return;} else result = operand1 / operand2; break;} s.push (result);} // Clear Operator Count Void Clear () {S.clearsTack ();} public: // Constructor, establish a value of a blank Calculator (Void) {} ​​// calculate the value of the expression void () {char Op; double operand; while (1) {cin >> OP; if (cin.eof ()) return; while (op! = '=') {switch (op) {case ' '

: Case '-': Case '*': Case '/': Compute (OP); Break; Default: cin.putback (op); CIN >> OPERAND; Enter (OPERAND); Break;} CIN >> OP; IF (cin.eof ()) Return;} cout << S.POP () << end1; clear ();}}}; # ENDIF / / // Calc.cpp # include "cagc.h"

Void main () {Calculator C; C.Run ();

转载请注明原文地址:https://www.9cbs.com/read-101647.html

New Post(0)