#10250: 出現 WA 可是找不到錯在哪


rain810926 (unknown)

學校 : 不指定學校
編號 : 52690
來源 : [59.127.113.216]
最後登入時間 :
2015-09-21 22:21:37
a017. 五則運算 | From: [59.127.113.216] | 發表日期 : 2015-09-19 17:38

#include<iostream>

#include <sstream>

#include<string>

#include<cstdlib>

using namespace std;

 

string inToPostfix(string infixString);

int postfixCompute(string postfixString);

int priority(char op);

 

int main(){

string infixString, postfixString;

 

 

while(getline(cin, infixString)){

postfixString = inToPostfix(infixString);

cout << postfixCompute(postfixString) <<endl;

 

}

 

return 0;

}

 

string inToPostfix(string infixString){

char stack[1000];

int top = 0;

 

istringstream in(infixString);

ostringstream postfixString;

string op;

 

while(in >> op){

switch(op[0]){

case '(':

stack[top++] = op[0];

break;

 

case '+': case '-': case '*': case '/': case '%':

if(top - 1 >= 0)

while(priority(stack[top-1]) >= priority(op[0]) && top - 1 >= 0 ) { 

                postfixString << stack[--top] << " ";                                         

            }

stack[top++] = op[0]; 

break;

 

case ')':

while(stack[top-1] != '('){

postfixString << stack[--top] << " ";

}

top--;

break;

 

default:

postfixString << op << " ";

break;

}

}

 

while(top - 1 >= 0){

postfixString << stack[--top] << " ";

}

 

return postfixString.str();

}

 

int postfixCompute(string postfixString){

char stack[1000];

int top = 0;

 

istringstream read(postfixString);

string op;

 

while(read >> op){

switch(op[0]){

case '+': 

stack[top - 2] = stack[top - 2] + stack[top - 1];

top--;

break;

 

case '-': 

stack[top - 2] = stack[top - 2] - stack[top - 1];

top--;

break;

 

case '*': 

stack[top - 2] = stack[top - 2] * stack[top - 1];

top--;

break;

 

case '/': 

stack[top - 2] = stack[top - 2] / stack[top - 1];

top--;

break;

 

case '%':

stack[top - 2] = stack[top - 2] % stack[top - 1];

top--;

break;

 

default:

stack[top++] = atoi(op.c_str());

break;

}

 

}

 

return stack[0];

}

 

int priority(char op){

switch(op){

case '*': case '/': case'%':

return 2;

 

case '+': case '-':

return 1;

 

default:

return 0;

}

}

 
ZeroJudge Forum