#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
void size_yunsuan(string input,string &a)
{
int i=0;
int length=input.size();
stack<char> stack1;
while(i<length)
{
//cout<<input[i]<<endl;
if(input[i]>='0'&&input[i]<='9')
a.push_back(input[i]);
if(input[i]=='+'||input[i]=='-')
{
if(stack1.empty()||stack1.top()=='('||stack1.top()=='+'||stack1.top()=='-')
{
stack1.push(input[i]);
}
else
{
while(!stack1.empty())
{
a.push_back(stack1.top());
stack1.pop();
}
}
}
if(input[i]=='(')
stack1.push(input[i]);
if(input[i]==')')
{
while(stack1.top()!='(')
{
a.push_back(stack1.top());
stack1.pop();
}
stack1.pop();
}
if(input[i]=='*'||input[i]=='/')
{
stack1.push(input[i]);
}
i++;
}
while(!stack1.empty())
{
a.push_back(stack1.top());
stack1.pop();
}
}
int yunsuan(string a)
{
if(a.size()==0)
return -1;
int i=0;
int length=a.size();
stack<int> temp;
int key=0;
int first,second;
while(i<length)
{
cout<<a[i]<<endl;
if(a[i]>='0'&&a[i]<='9')
temp.push(a[i]-'0');
else
{
switch (a[i])
{
case '+':
first=temp.top();
temp.pop();
second=temp.top();
temp.pop();
key=first+second;
temp.push(key);
break;
case '-':
first=temp.top();
temp.pop();
second=temp.top();
temp.pop();
key=second-first;
temp.push(key);
break;
case '*':
first=temp.top();
temp.pop();
second=temp.top();
temp.pop();
key=second*first;
temp.push(key);
break;
case '/':
first=temp.top();
temp.pop();
second=temp.top();
temp.pop();
key=second/first;
temp.push(key);
break;
// default:
//break;
}
}
++i;
}
return temp.top();
}
void calculate(string s)
{
string a;
size_yunsuan(s,a);
cout<<yunsuan(a)<<endl;;
}
int main()
{
string s("(3+5)/8");
calculate(s);
system("pause");
return 0;
}
用栈的知识实现四则运算(带括号的加减乘除)
最新推荐文章于 2022-04-18 19:44:35 发布