c++ 이용한 후위표식수식
조회수 457회
주어진 틀에서 stack class부분과 그를 이용해서 함수를 구성하는 것 까지는 해봤습니다.
그런데 token부분을 잘 몰라서 나머지 int main 부분만 구성을 못하고 있는데 그 부분을 도움을 받고 싶습니다. 또한 이외에 제가 작성한 전체적인 코딩에 수정해야 할 부분이 있다면 어떤 부분이 있는지 어떻게 고쳐야 하는지 알고 싶습니다.
- 2 3 + 3 5 + * -> 40.00
- 1.3 0 / 5.5 + -> zero division error
coding
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#define MAX_STACK_SIZE 100;
using namespace std;
// implement your stack here <<<
inline void error(char *str)
{
printf("%s\n", str);
exit(1);
}
class OperandStack
{
double 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(double e) //스택 생성자
{
if(isFull()) error ("stack full");
data[++top] = e;
}
double pop() //맨 위의 요소를 삭제하고 반환
{
if(isEmpty()) error ("stack empty");
return data[top--];
}
};
double calc_postfix(const vector<string>& expr){
double result = 0.0;
// fill here using your stack <<<
string c;
OperandStack st;
double var;
for(int i = 0; i < expr.size(); i++)
{
if(expr[i]=="+"||expr[i]=="-"||expr[i]=="*"||expr[i]=="/")
{
double val2 = st.pop();
double val1 = st.pop();
if(expr[i]=="+")
{
st.push(val1+val2);
}
else if(expr[i]=="-")
{
st.push(val1-val2);
}
else if(expr[i]=="*")
{
st.push(val1*val2);
}
else if(expr[i]=="/") {
if (val2 == 0) {throw std::runtime_error("zero division error");}
else st.push(val1 / val2);
}
}
else if(expr[i] >= "0" && expr[i] <= "9")
{
var=stod(expr[i]);
st.push(var);
}
}
return 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 them in the vector `expr`
while(getline(ss, token, ' '))
expr.push_back(token);
try {
cout << fixed << setprecision(2);
cout << calc_postfix(expr) << endl;
}catch(const std::runtime_error& error){
cout << error.what() << endl;
}
return 0;
}
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력