标签:put == sig inpu 整数 小数 运算 char ima
首先规定优先级,括号为最高优先级,乘号或除号为次优先级,加或减号为最低优先级,至于数字,碰到就直接输出即可。
既然是数字,就有小数,整数,正数,负数之分,还有关于二元运算符的输出,在括号内的二元运算符优先输出,优先级高的优先输出(当然括号不算啊)
根据题意,在输出时可分为以下几种情况。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
#include<queue>
#include<map>
using namespace std;
stack<char> sign;
char s[22];
map<char, int> mp;
int main()
{
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
mp['+'] = mp['-'] = 1;
mp['*'] = mp['/'] = 2;
mp['('] = mp[')'] = 3;
scanf("%s", s);
int len = strlen(s);
bool isfirst = true;
for(int i = 0; i < len; i++)
{
if((!i || (i && s[i-1] == '(')) && (s[i] == '+' || s[i] == '-'))
{
if(!isfirst)
printf(" ");
if(s[i] != '+')
printf("%c",s[i]);
while(i + 1 < len && (s[i+1] == '.' || (s[i+1] >= '0' && s[i+1] <= '9')))
{
++i;
printf("%c", s[i]);
}
if(isfirst)
isfirst = false;
}
else if(s[i] >= '0' && s[i] <= '9')
{
if(!isfirst)
printf(" ");
printf("%c", s[i]);
while(i + 1 < len && (s[i+1] == '.' || (s[i+1] >= '0' && s[i+1] <= '9')))
{
++i;
printf("%c", s[i]);
}
if(isfirst)
isfirst = false;
}
else if(s[i] == ')')
{
while(!sign.empty() && sign.top() != '(')
{
printf(" %c", sign.top());
sign.pop();
}
if(!sign.empty() && sign.top() == '(')
sign.pop();
}
else if(sign.empty() || (mp[s[i]] > mp[sign.top()]))
sign.push(s[i]);
else
{
while(!sign.empty() && sign.top() != '(')
{
printf(" %c", sign.top());
sign.pop();
}
sign.push(s[i]);
}
}
while(!sign.empty())
{
printf(" %c", sign.top());
sign.pop();
}
}
标签:put == sig inpu 整数 小数 运算 char ima
原文地址:https://www.cnblogs.com/KeepZ/p/11563413.html