1

Here in the following website: http://blockofcodes.blogspot.com/2014/08/postfix-evaluation-using-cpp-stack.html

If I enter value like 1.62 3.5 + 2.7 * then the return value is not in a decimal value.

I changed int to double, but it's still giving me an error. Can anyone give me an input on that?

Thank you!

    #include <stdio.h>
    #include <iostream>
    #include <stdlib.h>
    #include <stack>
    #include <string.h>

   using namespace std;

  bool isOperator(char ch)
 {
  if (ch=='+' || ch=='-' || ch=='*' || ch=='/')
      return true;
  else
      return false;
 }


int performOperation(int op1, int op2, char op)
{
  int ans;
  switch(op){
case '+':
    ans = op2 + op1;
    break;
case '-':
    ans = op2 - op1;
    break;
case '*':
    ans = op2 * op1;
    break;
case '/':
    ans = op2 / op1;
    break;
}
return ans;
 }


  int main()
  {
   char exp[1000], buffer[15];
   int i,op1, op2, len, j, x;
stack<int> s;
printf("Enter a Postfix Expression: ( e.g. 23 34 * )\n");
gets(exp);
len = strlen(exp);
j = 0;
for(i=0; i<len;i++){

    if(exp[i]>='0' && exp[i]<='9'){
        buffer[j++] = exp[i];
    }
    else if(exp[i]==' '){
        if(j>0){
            buffer[j] = '\0';
            x = atoi(buffer);
            s.push(x);
            j = 0;
        }
    }

    else if(isOperator(exp[i])){
        op1 = s.top();
        s.pop();
        op2 = s.top();
        s.pop();
        s.push(performOperation(op1, op2, exp[i]));
    }
}

printf("Answer is %d\n", s.top());

return 0;

}

JohnE
  • 13
  • 6

1 Answers1

0

Your storing your operands on a stack of integers, not floating point types.

Change stack<int> s to stack<double> s.

Also, op1 and op2 are also ints and should be doubles.

I stopped looking at this point. Make sure you're dealing with floating point types.

Steve
  • 6,334
  • 4
  • 39
  • 67