#30221: C++ 參考


cataholic.0000@gmail.com (貓奴)

學校 : 高雄市立高雄高級工業職業學校
編號 : 192061
來源 : [163.32.89.161]
最後登入時間 :
2024-04-02 10:25:34
a017. 五則運算 | From: [49.159.78.39] | 發表日期 : 2022-05-08 11:10

#include <iostream>
#include <string>
using namespace std;
int find_parenthese(string operations_A,int index_top){
    while(operations_A[index_top]!=')'){
        if(index_top>operations_A.length()){
            break;
        }else if(operations_A[index_top]=='('){
            index_top=find_parenthese(operations_A,index_top+1);
        }
        index_top++;
    }
    return index_top;
}
int Arithmetic(string operations,int index_top,int index_end){
    bool c=0;
    int value_1=0,value_2=1,operand=0,score;
    for(int i=index_top;i<index_end;i++){
        if(operations[i]!=' '){
            if(operations[i]>=48 && operations[i]<=57){
                score=0;
                for(i;i<index_end;i++){
                    if(operations[i]>=48 && operations[i]<=57){
                        score=score*10+operations[i]-48;
                    }else{
                        break;
                    }
                }
                i--;
                if(operand==0){
                    value_2*=score;
                }else if(operand==1){
                    value_2/=score;
                }else{
                    value_2%=score;
                }
                c=1;
            }else if(operations[i]=='+'){
                value_1+=value_2;
                value_2=1;
                operand=0;
                c=0;
            }else if(operations[i]=='-'){
                value_1+=value_2;
                value_2=-1;
                operand=0;
                c=0;
            }else if(operations[i]=='*'){
                operand=0;
            }else if(operations[i]=='/'){
                operand=1;
            }else if(operations[i]=='%'){
                operand=2;
            }else if(operations[i]=='('){
                if(operand==0){
                    value_2*=Arithmetic(operations,i+1,find_parenthese(operations,i+1)+1);
                }else if(operand==1){
                    value_2/=Arithmetic(operations,i+1,find_parenthese(operations,i+1)+1);
                }else{
                    value_2%=Arithmetic(operations,i+1,find_parenthese(operations,i+1)+1);
                }
                i=find_parenthese(operations,i+1);
                c=1;
            }
        }
        if(i==index_end-1 && c==1){
            value_1+=value_2;
        }
    }
    return value_1;
}
int main()
{
    string input_operations;
    while(getline(cin,input_operations)){
        cout<<Arithmetic(input_operations,0,input_operations.length())<<endl;
    }

    return 0;
}

 
ZeroJudge Forum