c++后缀表达式计算
.#include<iostream>using namespace std;class RPN{int a[999];//数字int top = 999;public:RPN(){for (int i = 0;i <999; i++)a[i] = { 0 };}~RPN(){}void push(int x){top--;a[top] = x;}int pop(){//删除栈顶
·
.
#include<iostream>
using namespace std;
class RPN
{
int a[999];//数字
int top = 999;
public:
RPN()
{
for (int i = 0;i <999; i++)
a[i] = { 0 };
}
~RPN(){}
void push(int x)
{
top--;
a[top] = x;
}
int pop()
{//删除栈顶数据;
char x = a[top];
top++;
return x;
}
bool empty()
{
if (top == 999)
return 1;
return 0;
}
int Val(char *data)
{//输入进来字符串
//然后判断,是数字还是符号,数字进栈,符号出栈
while (*data != '\0')
{
char ch = *data;
int z=0;
if (ch >= '0' && ch <= '9')
{
push(ch-'0');
}
else
{
int x, y;
x = pop();
y = pop();
switch (ch)
{
case'+':
z = x + y;
break;
case'-':
z = x - y;
break;
case'*':
z = x * y;
break;
case'/':
z = x / y;
break;
case'%':
z = x - y;
break;
default:
break;
}
push(z);
}
data++;
}
if (empty() == false)
{
int i = a[998];
return i;
}
return 0;
}
};
int main()
{
char data[999];
cin >> data;
RPN r;
cout<<r.Val(data)<<endl;
return 0;
}
点击阅读全文
更多推荐
所有评论(0)