📄 __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 + -