借助栈实现表达式的计算
【问题描述】输入一个算术表达式,包括加、减、乘、除、四种运算,表达式中可以出现小括号,通过栈先将中缀表达式转换为后缀表达式,然后计算出表达式的结果,具体内容可以参考殷人昆教材P95–100页
【输入形式】输入一个算术表达式,注意以#结束
【输出形式】输出表达式的结果,小数点后保留1位
【样例输入】
2.4+2*(1.3+2.4)-4.8/4#
【样例输出】
8.6
【样例说明】
其他测试数据:
输入:1.5+3.2# 输出: 4.7
输入:1.2+2*3# 输出: 7.2
代码如下:
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<cstring>
using namespace std;
template<class T>
class Stack
{
public:
Stack()
{
top = -1;
maxsize = 100;
data = new T[100];
}
~Stack()
{
delete[] data;
}
bool Push(T x)
{
if (top == maxsize - 1)
{
cout << "栈溢出" << endl;
return false;
}
data[++top] = x;
return true;
}
bool Pop(T& x)
{
if (top == -1)
{
cout << "栈空" << endl;
return false;
}
x = data[top--];
return true;
}
T Get_top()
{
return data[top];
}
bool Stack_empty()
{
if (top == -1)
return true;
else
return false;
}
private:
int top;
int maxsize;
T* data;
};
int isp(char x)
{
if (x == '-' || x == '+')
{
return 3;
}
else
{
if (x == '*' || x == '/')
{
return 5;
}
else
{
if (x == '(')
{
return 1;
}
else
{
if (x == ')')
return 6;
}
}
}
}
int icp(char x)
{
if (x == '-' || x == '+')
{
return 2;
}
else
{
if (x == '*' || x == '/')
{
return 4;
}
else
{
if (x == '(')
{
return 6;
}
else
{
if (x == ')')
return 1;
}
}
}
}
void Transform(char str[200])
{
Stack<char> temp;
char ch;
int count = 0;
cin.get(ch);
while (ch != '#')
{
if (ch == '.' || (ch >= '0' && ch <= '9'))
{
str[count] = ch;
count++;
cin.get(ch);
if (ch == '#')
str[count++] = ' ';
}
else
{
if (str[count - 1] != ' ')
str[count++] = ' ';
if (temp.Stack_empty())
{
temp.Push(ch);
cin.get(ch);
}
else
{
char t;
t = temp.Get_top();
if (icp(ch) > isp(t))
{
temp.Push(ch);
cin.get(ch);
}
else
if (icp(ch) < isp(t))
{
temp.Pop(t);
str[count] = t;
count++;
}
else
{
temp.Pop(t);
cin.get(ch);
}
}
}
}
while (!temp.Stack_empty())
{
char t;
temp.Pop(t);
str[count++] = t;
}
str[count] = '\0';
}
double Calctor(char str[200])
{
double result = 0;
Stack<double> num;
char t[10] = { 0 };
int count = 0;
double m, n;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] != ' ')
{
if (str[i] == '.' || (str[i] >= '0' && str[i] <= '9'))
{
t[count++] = str[i];
}
else
{
if (str[i] == '+')
{
num.Pop(m);
num.Pop(n);
result = n + m;
num.Push(result);
}
if (str[i] == '-')
{
num.Pop(m);
num.Pop(n);
result = n - m;
num.Push(result);
}
if (str[i] == '*')
{
num.Pop(m);
num.Pop(n);
result = n * m;
num.Push(result);
}
if (str[i] == '/')
{
num.Pop(m);
num.Pop(n);
result = n / m;
num.Push(result);
}
}
}
else
{
if (strlen(t) > 0)
{
num.Push(atof(t));
memset(t, '\0', sizeof(t));
count = 0;
}
}
}
num.Pop(result);
return result;
}
int main()
{
char str[200];
Transform(str);
double t = Calctor(str);
cout << fixed << setprecision(1) << t << endl;
return 0;
}