#include<iostream>
#include<stack>
using namespace std;
int f(const char* str, stack<char>& s)
{
int i = 0;
while(str[i] != '\0')
{
if(str[i] == '*')
{
char t = s.top();
s.pop();
t = (t-'0') * (str[i+1] - '0');
s.push(t + '0');
i += 2;
}
else if(str[i] == '/')
{
char t = s.top();
s.pop();
t = (t-'0') / (str[i+1] - '0');
s.push(t + '0');
i += 2;
}
else
{
s.push(str[i]);
i++;
}
}
while(!s.empty())
{
if(s.size() < 3)
{
break;
}
char t1 = s.top();
s.pop();
char t2 = s.top();
s.pop();
char t3 = s.top();
s.pop();
if(t2 == '+')
{
char t = (t3 - '0') + (t1 - '0');
s.push(t+'0');
}
else if(t2 == '-')
{
char t = (t3 - '0') - (t1 - '0');
s.push(t+'0');
}
}
int res = s.top() - '0';
return res;
}
int main()
{
stack<char> s;
char str[100] = {0};
cin>>str;
cout<<f(str,s)<<endl;
return 0;
}栈的应用,实现简单的不带括号的四则运算
最新推荐文章于 2021-10-12 17:56:38 发布
本文介绍了一种算法,该算法能够解析包含特定运算符的字符串表达式,并计算最终结果。通过使用栈来处理输入字符串,算法能够有效处理乘法、除法、加法和减法运算,同时支持字符串中嵌套的表达式。本文详细解释了算法的工作原理、实现细节以及如何在实际应用中使用此算法。
1378

被折叠的 条评论
为什么被折叠?



