//
// calculate.cpp
//
#include "calculate.hpp"
const int MaxSize = 50;
int main()
{
char exp[] = "(56-20)/(4+2)";
char postexp[MaxSize];
trans(exp, postexp);
printf("中缀表达式:%s\n", exp);
printf("后缀表达式:%s\n", postexp);
printf("表达式的值:%g\n", compvalue(postexp));
return 0;
}
//
// calculate.hpp
//
#ifndef calculate_hpp
#define calculate_hpp
#include "stack.h"
#include <stdio.h>
#include <iostream>
struct
{
char ch;
int prio;
}lp[] = {{'=', 0}, {'+', 2}, {'-', 2}, {'*', 4}, {'/', 4}, {'(', 1}, {')', 6}},
rp[] = {{'=', 0}, {'+', 3}, {'-', 3}, {'*', 5}, {'/', 5}, {'(', 6}, {')', 1}};
int prio_left(char ch)
{
for(int i = 0; i < 7; i++)
{
if(ch == lp[i].ch)
return lp[i].prio;
}
return -1;
}
int prio_right(char ch)
{
for(int i = 0; i < 7; i++)
{
if(ch == rp[i].ch)
return rp[i].prio;
}
return -1;
}
void trans(char exp[], char postexp[])
{
// 等号入栈,遍历中缀,
// 如果是数则存入postexp且结尾加‘#’,
// 比较栈顶元素左优先级和数组元素右优先级,
// 如果数组的元素优先级比栈顶元素大则入栈,小则弹栈并存入postexp,优先级相等(成对括号)括号成对则出栈,
// 遍历结束将栈内等号前符号弹栈存入postexp
stack a;
a.init();
a.push('=');
char *p = exp, *pp = postexp;
// for( ; *p != '\0'; p++)
while (*p!='\0')
{
if(*p >= '0' && *p <= '9')
{
while(*p != '\0' && *p >= '0' && *p <= '9')
{
*pp = *p;
pp++;
p++;
}
*pp = '#';
pp++;
// p++;
} else {
if(*p == '\0')
break;
int prio_r = prio_right(*p);
int prio_top = prio_left(a.top_elem());
if(prio_r > prio_top)
{
a.push(*p);
p++;
}
if(prio_r < prio_top)
{
char e;
e = a.pop();
*pp = e;
pp++;
}
// prio_top = prio_left(a.top_elem());
if(prio_r == prio_top)
{
a.pop();
p++;
}
}
}
char ch = a.pop();
while(ch != '\0' && ch != '=')
{
*pp = ch;
pp++;
ch = a.pop();
}
*pp = '\0';
}
double compvalue(char postexp[])
{
// switch
// 遇到数字则入栈,
// 遇到算术符则出栈两个元素,进行相应的运算,将结果入栈
stack st;
st.init();
double a,b;
for (char *pd = postexp; *pd != '\0'; pd++)
{
switch (*pd) {
case '+':
a = st.pop();
b = st.pop();
st.push(a + b);
break;
case '-':
a = st.pop();
b = st.pop();
st.push(b - a);
break;
case '*':
a = st.pop();
b = st.pop();
st.push(a * b);
break;
case '/':
a = st.pop();
b = st.pop();
if(a != 0)
st.push(b / a);
else
{
std::cout << "Error!";
return 0;
}
break;
default:
int d = 0;
while(*pd >= '0' && *pd <= '9')
{
d = 10 * d + *pd - '0';
pd++;
}
st.push(d);
break;
}
}
return st.top_elem();
}
#endif /* calculate_hpp */
//
// stack.h
//
#ifndef stack_h
#define stack_h
static const int Size = 50;
struct stack
{
private:
double data[Size];
int top;
public:
void init()
{
top = 0;
}
double pop()
{
if(top == 0)
return -1;
else
{
double e = data[top-1];
top--;
return e;
}
}
bool push(double ch)
{
if(top >= Size)
return false;
else
{
top++;
data[top-1] = ch;
return true;
}
}
double top_elem()
{
if(top == 0)
return -1;
else
return data[top-1];
}
};
#endif /* stack_h */