1

我的以下代码工作正常,但只输出第二个输入,而不是第一或第三个输入。我的代码应该从控制台获取完全带括号的表达式并将其转换为后缀表达式,然后该后缀表达式应该以模 10 进行计算。因此,所有结果(包括中间结果)都是 {0, 1, ..., 9} 中的单个十进制数字. 我只需要在堆栈中存储单个数字。

我的输入和输出如下所示。我只正确输入了第二个输入。

请指教。

Expression 1: (((2+(5^2))+7) 

Answer: 
252^+7+

4 in modulo 10

Expression 2: ((((2+5)*7)+((9*3)*2))^2)

Answer: 
25+7*93*2*+2^

9 in modulo 10

Expression 3: ((((2*3)*(4*6))*7)+(((7+8)+9)*((2+4)*((7+8)+9))))

Answer: 
23*46*7*789++24+78+9+**+

4 in modulo 10

我的代码:

#include <iostream>
#include <string>
#include<sstream>

using namespace std;

class STACK {
private:
   char *s;
   int N;
public:
   STACK(int maxN) {
       s = new char[maxN];
       N = 0;
   }
   int empty() const {
       return N == 0;
   }
   void push(char item) {
       s[N++] = item;
   }
   char pop() {
       return s[--N];
   }
};

int main() {
   string infixExpr;
   string postfixExpr = "";
   cout << "Enter infix expression:" << endl;
   cin >> infixExpr;  //converting to postfix read from the input
   int N = infixExpr.size(); //strncpy(a, infixExpr.c_str(), N);
   STACK ops(N);
   char ch;
   for (int i = 0; i < N; i++) {
       if (infixExpr[i] == ')')
       {
           ch = ops.pop();
           postfixExpr.push_back(ch);
       }
       if ((infixExpr[i] == '+') || (infixExpr[i] == '*')   || (infixExpr[i] == '^'))
           ops.push(infixExpr[i]);
       if ((infixExpr[i] >= '0') && (infixExpr[i] <= '9'))
       {
           //cout << infixExpr[i] << " ";
           postfixExpr.push_back(infixExpr[i]);
       }
   }
   cout <<"Answer :"<<endl;
   cout <<postfixExpr <<endl; //evaluate post fix expression
   N = postfixExpr.size();
   STACK save(N);
   int result;
   int num;
   int count = 0;
    string temp = "";
   for (int i = 0; i < N; i++) {
   //   cout << " Expr[i] " << postfixExpr[i] << endl;
       if (postfixExpr[i] == '+')
           save.push((save.pop() + save.pop()) % 10);
       if (postfixExpr[i] == '*')
           save.push((save.pop() * save.pop()) % 10);
       if (postfixExpr[i] == '^') {
           count = save.pop() - '0';
           num = save.pop() - '0'; //cout << result << "- " <<"-" <<count<<endl;
           result = 1;
           for(int j = 1; j <= count; j++)
           {
               result = result * num;
               result = result % 10;
           }
           stringstream convert;
           convert << result;//add the value of Number to the characters in the stream
           temp = convert.str();//set Result to the content of the stream
           save.push(temp[0]);
       }
       if ((postfixExpr[i] >= '0') && (postfixExpr[i] <= '9'))
       {
           save.push(postfixExpr[i]);
       }
   }
   cout << save.pop() <<" in module 10"<< endl;
   return 1;
}
4

0 回答 0