c++ vector

조회수 821회

중위표기수식을 후위표기수식으로 전환 후 계산하는 프로그램을 코딩했습니다.

근데

  1. input = ( 6.0 / 3.0 ) + 4.0 * 0.4 , output = 3.60
  2. input = 6 / 3 + 4 * 0.4 / 0 , output = zero division error 이렇게 예시 입출력을 넣으면 위처럼 나와야 하는데 1번 입력을 넣었더니 'stack is empty'가 나옵니다.

postfix부분에 사용된 operandstack이나 후위표기수식으로 변환된 식을 계산하는 프로그램은 사이트 상에서 맞다고 확인이 된 부분이어서 중위표기수식의 arraystack이나 vector의 우선순위 정하는 부분이 잘못된 부분이 있는 것 같은데 저는 할 수 있는데까지 했는데 vector부분을 어떻게 바꿔줘야 제가 원하는 출력값이 나올 수 있을지 코드 수정을 받고 싶습니다. 도와주세요 ㅠㅠ

작성한 코드

#include <vector>

#include <string>

#include <sstream>

#include <iomanip>

#inlcdue <iostream>

using namespace std;


#define MAX_STACK_SIZE 100


// implement your (templated) stack here <<<

inline void error(string str)

{

 cout << str << '\n';

 exit(1);

}


inline int precedence(char op)

{

 switch(op)

{

 case '(': case ')': return 0;

 case '+': case '-': return 1;

 case '*': case '/': return 2;

}

 return -1;

}


 class ArrayStack

{

  string data[MAX_STACK_SIZE];

   int top;


public:

  ArrayStack() {

    top = -1;

 }

   ~ArrayStack(){}

 bool isEmpty() {

   return top == 1;

}

  bool isFull(){

   return top == MAX_STACK_SIZE - 1;

}

 void push(string elem) {

   if(isFull())

        error("Stack is full");

    data[++top] = elem;

}

 string pop() {
    if(isEmpty())

 error("Stack is empty");
    return data[top--];
}
string peek() {
    if(isEmpty())
        error("Stack is empty");

  return data[top];

}

};


class OperandStack

{

string data[MAX_STACK_SIZE];

int top;



public:

 OperandStack() { // 스택 생성자

  top = -1;

}

bool isEmpty() {

 return top == -1;

 }

 bool isFull() {

 return top == MAX_STACK_SIZE - 1;

 }

 void push(string elem) {

  if (isFull())

    error("Stack is full");

  data[++top] = elem;

 }

 string pop(){

  if (isEmpty())

   error("Stack is empty");

   return data[top--];

}

};


vector<string> infix_to_postfix(const vector<string>& expr) {

vector<string> postfix;

// fill here using your stack <<<
ArrayStack s;
string op;

for(int i = 0; i < expr.size(); i++) {
    if(expr[i][0] == '(') {
        s.push(expr[i]);
    } else if(expr[i][0] == ')') {
        while(!s.isEmpty()) {
            op = s.pop();
            if(op[0] == '(') break;
            else {
                postfix.push_back(op);
            }
        }
    } else if(expr[i][0] == '+' || expr[i][0] == '-' || expr[i][0] == '*' || expr[i][0] == '/') {
        while(!s.isEmpty()) {
            op = (s.peek())[0];
            if(precedence(expr[i][0]) <= precedence(op[0]))
                postfix.push_back(s.pop());
            else break;
        }
        postfix.push_back(expr[i]);
    } else {
        postfix.push_back(expr[i]);
    }
}
return postfix;
}

double calc_postfix(const vector<string>& expr){
double result = 0.0;

// fill here using your stack <<<
OperandStack st;

for (int i = 0; i < expr.size(); i++)
{
    if (expr[i] == "+" || expr[i] == "-" || expr[i] == "*" || expr[i] == "/")
    {
        double operand2 = stod(st.pop());
        double operand1 = stod(st.pop());

        if (expr[i] == "+")
            st.push(to_string(operand1 + operand2));
        else if (expr[i] == "-")
            st.push(to_string(operand1 - operand2));
        else if (expr[i] == "*")
            st.push(to_string(operand1 * operand2));
        else if (expr[i] == "/")
        {
            if (operand2 == 0)
                throw runtime_error("zero division error");
            else
                st.push(to_string(operand1 / operand2));
        }
    }
    else
        st.push(expr[i]);
}

return stod(st.pop());
}

int main(){
vector<string> expr;
string line, token;

getline(cin, line);
stringstream ss(line);

// tokenize the given line and sequentially store each of tokens in the vector `expr`
while(getline(ss, token, ' '))
    expr.push_back(token);

expr = infix_to_postfix(expr);

try {
    cout << fixed << setprecision(2);
    cout << calc_postfix(expr) << endl;
}catch(std::runtime_error error){
    cout << error.what() << endl;
}

return 0;
}
  • (•́ ✖ •̀)
    알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)