プログラミング問題:四則演算


タイトルの説明
次のインタフェースを実装してください.
/*機能:四則演算
*入力:strExpression:文字列形式の算術式(3+2*{1+2*[-4/(8-6)+7]})
*戻る:算術式の計算結果
     */
    public static int calculate(String strExpression)
    {
/*実現してください*/
        return 0;
    } 
制約:
  • pucExpression文字列の有効文字には、['0'-'9'],'+','-','*','(',')','[','],'{','}'が含まれます.
  • pucExpression算術式の有効性は呼び出し者によって保証される. 

  •  
    説明を入力:
     
       

    输入一个算术表达式

    输出描述:
     
       

    得到计算结果

    输入例子:
    3+2*{1+2*[-4/(8-6)+7]}

    出力例:
    25
      :     ;   0;

    #include
    #include #include #include using namespace std; int is_parenthese(char c)/小かっこ{if(c='('||c=')'){return 1;else return 0; } intperior(char c)//判断してオペレータの優先度{if(c==='('|c==')')return 1;else if(c=='+'|c='-')return 2;else return 3;///if(c='*'*'|='/')}void check(char c,stack&cnt 2,deque&cnt 3)//判断オペレータの優先度{if(cnt 2.empty(){//cnt 2現在空の場合、直接オペレータの優先度cスタックcnt 2.push(c);return;}if(is_parenthese(c){//オペレータがカッコif(c='('){//左カッコを入力するとcnt 2.push(c)}Else{//右かっこと入力されたときwhile(cnt 2.top()!='('){//左かっこがchar tmp=cnt 2.top();cnt 3.push_back(tmp);cnt 2.pop();cnt2.pop();}}Else{//かっこでない場合、char tmp=cnt 2.top()//現在のスタックトップの位置if(perior(c)<=perior(tmp)){//現在のオペレータの優先度がcnt 2のトップより低い場合cnt 3.push_back(tmp)//cnt 2トップのオペレータをcnt 3;cnt 2.pop();check(c,cnt 2,cnt 3); 現在の入力cと更新後のcnt 2との比較を循環する}else{cnt 2.push(c);////////////////////////////cが現在のスタックトップオペレータより優先度が大きい場合、cをcnt 2スタックに入れる}}void Allocate(deque&cnt 1,stack&cnt 2,deque&cnt 3)///接尾辞{while(!cnt 1.empty(){char c=cnt 1.front();cnt 1.pop_front();if(c>='0'&c<='9'''&c<='9'''';cnt(c<='9''';9'';){cnt 3.push_back(c);}else{check(c, cnt2, cnt3);}}while(!cnt 2.empty(){//入力終了後、cnt 2の残りのオペレータをchar tmp=cnt 2.top();cnt 3.push_back(tmp);cnt 2.pop()}}void Calculate(deque&cnt 3,stack&cnt 4){while(!cnt 3.empty(){char c=cnt 3.front();cnt 3.pop_front();if(c>='0'&&c<='9'){//オペランドint op=c-'0';//ASCALLコードをリアルな数値cnt 4.push(op);}else{//////オペレータの場合int op 1=cnt 4.top();cnt 4.pop();int op 2=cnt 4.top();cnt 4.pop();switch(c){case'+':cnt 4.push(op 2+op 1);break;case'-':cnt 4.push(op 2-op 1);break;break;case'*':cnt 4.push(op 2*op 1);break;case'/':cnt 4.push(op 2/op 1);break;break;case'/':cnt 4.push(op 2/op 1);break;;}}}int main(){string str;cout<<<「計算する演算子を入力してください:」<str;deque cnt 1;//接尾辞(計算する演算子)dequeを格納する利点は、stack cnt 2を前から後から操作できることです;//オペレータdeque cnt 3を格納する//接尾辞stack cnt 4を格納する//接尾辞計算支援注意:タイプの変化for(int i=0;i