WA on #3 #9 #10,code:
#include <iostream>
#include <cctype>
#include <cmath>
const int N = 105;
int St[N];
char st[N];
bool higher(char c,char _c){
if (c == '+' || c == '-') return false;
if (c == '*' || c == '/') return _c == '+' || _c == '-';
return true;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("P1175.in","r",stdin);
freopen("P1175.out","w",stdout);
#endif
std::cin.tie(0)->sync_with_stdio(0);
int top = 0;
std::string in,post = "";
std::cin >> in;
for (char c : in){
if (isdigit(c)) post += c,post += ' ';
else{
if (c == '(') st[++top] = c;
else if (c == ')'){
while (top && st[top] != '(')
post += st[top],post += ' ',--top;
if (top) --top;
}
else if (!top || st[top] == '(' || higher(c,st[top])) st[++top] = c;
else{
while (top && st[top] != '(' && !higher(c,st[top]))
post += st[top],post += ' ',--top;
st[++top] = c;
}
}
}
while (top) post += st[top],post += ' ',--top;
post.pop_back();
std::cout << post << '\n';
for (int i = 0;i < post.length();i++){
if (isdigit(post[i])) St[++top] = post[i] - '0';
else if (post[i] != ' '){
int a = St[top--],b = St[top--],tmp,pos = i - 2;
switch (post[i]){
case '+':tmp = b + a;break;
case '-':tmp = b - a;break;
case '*':tmp = b * a;break;
case '/':tmp = b / a;break;
case '^':tmp = pow(b,a);break;
default:break;
}
St[++top] = tmp;
post.erase(i - 1,2);
while (pos >= 0 && isdigit(post[pos])) post.erase(pos,1),pos--;
post.erase(std::max(pos,0),1);
pos--;
while (pos >= 0 && isdigit(post[pos])) post.erase(pos,1),pos--;
post.erase(std::max(pos,0),1);
pos--;
if (pos + 1 >= 0) post.insert(pos + 1,' ' + std::to_string(tmp));
else post.insert(0,std::to_string(tmp) + ' ');
i = std::max(pos + 2,0) + std::to_string(tmp).length();
std::cout << post << '\n';
}
}
return 0;
}
最好能告诉我错因,或者告诉我哪行错了也行