?? __calc.cpp
字號:
/*
利用棧實現簡單計算器的例子(Calculator)
選擇自 YangJq 的 Blog
關鍵字 利用棧實現簡單計算器的例子(Calculator)
NOTE:只接受 逆波蘭 表達式 -- by szh
*/
/* Calculator.h */
//#ifndef __CALCULATOR_H__
//#define __CALCULATOR_H__
#include <iostream>
#include <stack>
using namespace std;
class Calculator
{
private:
//存放操作數的棧
stack<double> s;
//將一個double型操作數壓入棧中
void Enter(double operand)
{
s.push(operand);
}
//從棧頂讀取兩個操作數
int GetTwoOperands(double &operand1, double &operand2)
{
if (s.empty())
{
cerr << "No operand to pop!" << endl;
//s.ClearStack();
while (!s.empty()) s.pop();
return 0;
}
operand2 = s.top(); s.pop(); //NOT operand1 !!
if (s.empty())
{
cerr << "No operand to pop!" << endl;
//s.ClearStack();
while (!s.empty()) s.pop();
return 0;
}
operand1 = s.top();s.pop(); //NOT operand2 !!
return 1;
}
//將調用GetTwoOperands讀取的兩個操作數做運算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();
while (!s.empty()) s.pop();
return;
}
else
result = operand1 / operand2;
break;
}
s.push(result);
}
//清空操作數棧
void Clear()
{
while (!s.empty()) s.pop();
//s.ClearStack();
}
public:
//構造函數,建立一空棧
Calculator(void) {}
//計算表達式的值
void Run()
{
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.top() << endl; s.pop();
Clear();
}
}
};
//#endif
//////////////////////////////////////////////////////////////////
// Calc.cpp
//#include "calc.h"
void main()
{
Calculator c;
c.Run();
}
/*
1 2 -
=
-1
1 2 /
=
0.5
1 2 + 3 * =
9
1 2 + 3 / =
1
123 3 /
=
41
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -