这是在学习数据结构时写的代码,表达式求值。
设计一个程序,演示用算符优先法对算术表达式求值的过程。利用算符优先关系,实现对算术四则混合运算表达式的求值。
(1)输入的形式:表达式,例如2*(3+4)
包含的运算符只能有'+' 、'-' 、'*' 、'/' 、'('、 ')';
(2)输出的形式:运算结果,例如2*(3+4)=14;
(3)程序所能达到的功能:对表达式求值并输出
#include <iostream>
#include "touwenjian.h"
#include <string>
#include <cmath>
int main()
{
char m;
cout << "请输入表达式,可以使用+ - * / % ^ 科学技术法示例:T3代表10^3" << endl;
Calculator<double> cal;
cal.Run();
cout << "是否继续y表示继续,其他表示结束" << endl;
cin >> m;
while (m=='y')
{
switch (m)
{
case 'y':
{
cal.Run();
cout << "是否继续y表示继续,其他表示结束" << endl;
cin >> m;
break;
}
}
}
getchar();
getchar();
return 0;
}
#ifndef _TOUWENJIAN_H
#define _TOUWENJIAN_H
#include <cmath>
#include "sq_stack.h"
#include "utility.h"
#include "lk_stack.h"
#include "node.h"
#include <stack>
template<class ElemType>
class Calculator
{
private:
LinkStack<ElemType>opnd;
LinkStack<char>optr;
bool IsOperator(char ch);
int OperRank(char op,char np);
double Operate(double left, char zhongjian, double right);
public:
void Run();
Calculator() {};
virtual ~Calculator() {};
};
template<class ElemType>
void Calculator <ElemType>::Run()
{
optr.Clear();
opnd.Clear();
optr.Push('=');
opnd.Push(0);
char ch;
char op;
char np;
double a1, a2, a3, shuzi;
ElemType operand;
ch = getchar();
char optrTop;
optr.Top(optrTop);
while (optrTop != '=' || ch != '=')
{
if (!IsOperator(ch))
{
cin.putback(ch);
cin >> operand;
opnd.Push(operand);
cin >> ch;
}
else
{
if (OperRank(optrTop,ch)==-1)
{
optr.Push(ch);
cin >> ch;
}
else if (OperRank(optrTop, ch) == 1)
{
opnd.Pop(a1);
opnd.Pop(a2);
optr.Pop(optrTop);
shuzi = Operate(a2, optrTop, a1);
opnd.Push(shuzi);
}
else if (OperRank(optrTop, ch) == 0 )
{
optr.Pop(optrTop);
cin >> ch;
}
else cout << "表达式错误" << endl;
}
optr.Top(optrTop);
}
opnd.Pop(a3);
cout << a3 << endl;
}
template<class ElemType>
bool Calculator <ElemType>::IsOperator(char ch)
{
if (ch != '+'&&ch != '-'&&ch != '='&&ch != '*'&&ch != '/'&&ch != '('&&ch != ')'&&ch != '%'&&ch != '^'&&ch != 'T')
return false;
else return true;
}
template<class ElemType>
int Calculator <ElemType>::OperRank(char op,char np)
{
int x, y;
if (op == '+' || op == '-') x=3;
if (op == '*' || op == '/'||op=='%') x=5;
if (op == '(') x = 1;
if (op == ')') x = 6;
if (op == '=') x = 0;
if (op == 'T') x = 8;
if (op == '^') x = 12;
if (np == '+' || np == '-') y=2;
if (np == '*' || np == '/' || np == '%') y = 4;
if (np == '(') y = 6;
if (np == ')') y = 1;
if (np == '=') y = 0;
if (np == 'T') y = 7;
if (np == '^') y = 11;
if (x > y)
return 1;
else if (x < y)
return -1;
else return 0;
}
template<class ElemType>
double Calculator <ElemType>::Operate(double right, char zhongjian, double left)
{
switch(zhongjian)
{
case '+': return right + left;
break;
case '-': return right - left;
break;
case '*': return right * left;
break;
case '/': return right/left;
break;
case '%': return int(right)%int(left);
break;
case 'T':return right*(pow(10.0, left));
break;
case '^':return pow(right, left);
break;
}
}
#endif // !_TOUWENJIAN_H