您的位置:首页 > 其它

简单的表达式求值

2015-08-31 10:55 225 查看
#include <bits/stdc++.h>
using namespace std;
#define M 100
char ops[7] = {'+', '-', '*', '/', '(', ')', '='};
char cmp[7][7]= {{'>', '>', '<', '<', '<', '>', '>'},
{'>', '>', '<', '<', '<', '>', '>'},
{'>', '>', '>', '>', '<', '>', '>'},
{'>', '>', '>', '>', '<', '>', '>'},
{'<', '<', '<', '<', '<', '=', ' '},
{'>', '>', '>', '>', ' ', '>', '>'},
{'<', '<', '<', '<', '<', ' ', '='}
};
bool check(char ch)
{
for (int i = 0; i < 7; i++)
if (ch == ops[i])
return true;
return false;
}
char C(char ch1, char ch2)
{
int i, m, n;
for (i = 0; i < 7; i++)
{
if (ch1 == ops[i])
m = i;
if (ch2 == ops[i])
n = i;
}
return   cmp[m]
;

}
void cal(int x, char op, int y, int &z)
{
switch (op)
{
case '+':
z = x + y;
break ;
case '-':
z = x - y;
break ;
case '*':
z = x * y;
break ;
case '/':
z = x / y;
break ;

}
}

void work(char *str, int &result)
{
int a, b, v;
char ch, op;
int temp, i = 0;
stack <char> oper;
stack <int> num;
oper.push('=');
ch = str[i++];
while (ch != '=' || oper.top() != '=')
{
if (check(ch))
{
switch (C(oper.top(), ch))
{
case '<':
oper.push(ch);
ch = str[i++];
break;
case '=':
oper.pop();
ch = str[i++];
break;
case '>':
op = oper.top();
oper.pop();
b = num.top();
num.pop();
a = num.top();
num.pop();
cal(a, op, b, v);
num.push(v);
break;

}
}
else
{
temp = ch - '0';
num.push(temp);
ch=str[i++];
}

}
result = num.top();
printf("%d\n",result);
}
int main()
{
int i = 0;
int result;
char *str;
str = new char[M];
cin >> str[i];
while (str[i] != '=')
{
cin >> str[++i];
}
work(str, result);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: