数据结构-栈的应用之逆波兰计算器的实现11
程序员文章站
2022-05-24 23:53:52
...
栈的应用之逆波兰计算器的实现
1.先看看逆波兰表达式是个什么东西
2.用代码实现:
至于TyStack可以查看我的上一篇文章数据结构-栈10
void main()
{
TyStack<double> m_stack;
char str[10] = { 0 };//主要用来缓存输入的数字
printf("请输入逆波兰表达式(#:结束),以空格代表每个数字的分割\n");
char c = ' ';
scanf("%c", &c);
int i = 0;
while (c != '#')
{
while (isdigit(c)||'.' == c)
{
str[i++] = c;
str[i] = '\0';
scanf("%c", &c);
if (' ' == c )
{
m_stack.push(atof(str));
i = 0;
break;
}
}
switch (c)
{
case '+':
{
double a = m_stack.top();
m_stack.pop();
double b = m_stack.top();
m_stack.pop();
m_stack.push(a + b);
}
break;
case '-':
{
double a = m_stack.top();
m_stack.pop();
double b = m_stack.top();
m_stack.pop();
m_stack.push(b - a);
}
break;
case '*':
{
double a = m_stack.top();
m_stack.pop();
double b = m_stack.top();
m_stack.pop();
m_stack.push(b * a);
}
break;
case '/':
{
double a = m_stack.top();
m_stack.pop();
double b = m_stack.top();
m_stack.pop();
if (0 == a)
{
printf("除数不能为0\n");
return;
}
m_stack.push(b / a);
}
break;
default:
break;
}
scanf("%c", &c);
}
double t = m_stack.top();
m_stack.pop();
printf("计算结果:%f\n", t);
system("pause");
}
结果:
(1-2)*(4+5)==>1 2 - 4 5 + *
(9+3)/(6-2)==>9 3 + 6 2 - /