#35606: 錯誤求解


s110151@student.cysh.cy.edu.tw (a6a6a6)

學校 : 國立嘉義高級中學
編號 : 203583
來源 : [101.9.134.24]
最後登入時間 :
2024-05-15 12:48:05
a017. 五則運算 | From: [101.9.113.150] | 發表日期 : 2023-06-08 10:25

 #include <bits/stdc++.h>
using namespace std;
int sum(int a,string b,int c)
{
        if(b=="+")
            return(a+c);
        else if(b=="-")
            return(a-c);
        else if(b=="*")
            return(a*c);
        else if(b=="/")
            return(a/c);
        else if(b=="%")
            return(a%c);
         
}
int main() {
string s, c;
while(getline(cin, s)) {
stack <string> st;
vector <string> ans;
stringstream ss;
ss << s;
while(ss >> c) {
if(c == ")")
                {
while(st.top() != "(")
{
ans.push_back(st.top());
st.pop();
}
st.pop();
}
            else if(c == "(")
            {
st.push("(");
}
            else if(c == "*" || c == "/"||c=="%")
            {
while(!st.empty() && (st.top() == "*" || st.top() == "/")||c=="%")
                {
ans.push_back(st.top());
st.pop();
}
st.push(c);
}
else if(c == "+" || c == "-")
                {
while(!st.empty() && (st.top() == "*" || st.top() == "/" || st.top() == "+" || st.top() == "-")) {
ans.push_back(st.top());
st.pop();
}
st.push(c);
}
            else
            {
ans.push_back(c);
}
}
 
while(!st.empty())
        {
ans.push_back(st.top());
st.pop();
}
stack < int > skk;
stringstream sss;
cout<<ans.size()<<endl;
int num=0;
for(int i=0;i<ans.size();i++)
{
   if(ans[i]=="+"||ans[i]=="-"||ans[i]=="*"||ans[i]=="/"||ans[i]=="%")
   {
       int fir=0,sec=0;
       sec=skk.top();
       skk.pop();
       fir=skk.top();
       skk.pop();
       skk.push(sum(fir,ans[i],sec));
   }
   else
   {
   sss<<ans[i];
   sss>>num;
   skk.push(num);
   }
}
        cout<<skk.top()<<endl;
        skk.pop();
}
}
 
 
 
 
ZeroJudge Forum