表达式求值
#ifndef OPND_H
#define OPND_H
#include<iostream>
using namespace std;
template <typename T>
class OPND
{
template <typename T>
friend ostream & operator<<(ostream & os, OPND<T> & bs);
public:
OPND(int size);
~OPND();
void Push(T x);
T Pop();
private:
int Num2;
T *data;
int top;
};
template <typename T>
ostream & operator<<(ostream & os, OPND<T> & bs)
{
int i = bs.Num2;
os << bs.data[i-1];
return os;
}
template <typename T>
OPND<T>::OPND(int size)
{
data = new T[size];
Num2 = size;
top = -1;
}
template <typename T>
OPND<T>::~OPND(){
delete[] data;
}
template <typename T>
void OPND<T>::Push(T x)
{
if (top == Num2 - 1)throw"上溢";
data[++top] = x;
}
template <typename T>
T OPND<T>::Pop()
{
if (top == -1)throw"下溢";
return data[top--];
}
#endif
#ifndef OPTR_H
#define OPTR_H
#include<iostream>
using namespace std;
template <typename T>
class OPTR
{
template <typename T>
friend ostream & operator<<(ostream & os, OPTR<T> & bs);
template <typename T>
friend ostream & operator>(ostream & os, OPTR<T> & bs);
public:
OPTR(int size);
~OPTR();
void Push(T x);
T Pop();
private:
int Num1;
T *data;
int top;
};
template <typename T>
ostream & operator>(ostream & os, OPTR<T> & bs)
{
char zxh = bs.Pop();
char zxh2 = bs.Pop();
if (zxh == '*' || zxh == '/')
{
os << zxh;
bs.Push(zxh2);
}
if (zxh == '+' || zxh == '-')
{
if (zxh2 == '*' || zxh2 == '/')
{
os << zxh2;
bs.Push(zxh);
}
else
{
os << zxh;
bs.Push(zxh2);
}
}
}
template <typename T>
ostream & operator<<(ostream & os, OPTR<T> & bs)
{
int i = bs.Num1;
os << bs.data[i-1];
return os;
}
template <typename T>
OPTR<T>::OPTR(int size)
{
data = new T[size];
Num1 = size;
top = -1;
//data[0] = '#';
}
template <typename T>
OPTR<T>::~OPTR(){
delete[] data;
}
template <typename T>
void OPTR<T>::Push(T x)
{
if (top == Num1 - 1)throw"上溢";
data[++top] = x;
}
template <typename T>
T OPTR<T>::Pop()
{
if (top == -1)throw"下溢";
return data[top--];//此处要求弹出顶部元素来参与运算所以不能全部的弹出
}
#endif
#include"OPND.h"
#include"OPTR.h"
#include<iostream>
using namespace std;
int main()
{
int num;
cout << "请输入您想运算的运算式中的数字的个数:";
cin >> num;
OPTR<char> tr(num);
OPND<int> nd(num);
char ch; int a[100];
char b[100];
char ch1='+';
int sum;
cout << "输入您要运算的一位的整数:";//上接INT sum
for (int i = 0; i < num; i++)
{
cin >> a[i];
nd.Push(a[i]);
}
cout << "请输入对应的运算符(以#号开始录入):";
for (int i = 0; i < num ; i++)
{
cin >> b[i];
tr.Push(b[i]);
}
while (ch1!= '#')
{
char zxh = tr.Pop();
char zxh2 = tr.Pop();
if (zxh == '*' || zxh == '/')
{
ch = zxh;
tr.Push(zxh2);
ch1 = zxh2;
}
if (zxh == '+' || zxh == '-')
{
if (zxh2 == '*' || zxh2 == '/')
{
ch = zxh2;
tr.Push(zxh);
ch1 = zxh;
}
else
{
ch = zxh;
tr.Push(zxh2);
ch1 = zxh2;
}
}
if (ch=='+')
sum = nd.Pop() + nd.Pop();
if (ch=='-')
sum = nd.Pop() - nd.Pop();
if (ch=='*')
sum = nd.Pop() * nd.Pop();
if (ch=='/')
sum = nd.Pop() / nd.Pop();
nd.Push(sum);
}
cout << "您要求的表达式的值为:" << sum << endl;
return 0;
}