Question

I have final exam tomorrow in data structures 'LAB'!

I have a Problem when I run this code! This code evaluates the postfix expression. It's so simple..but i don't know why when I run it and try to divide e.g : 6/2. it prints out 2 instead of 3!

The + and - and * all are correct but the problem with division! Do you think the problem with library in my compiler!!

I use Code::Blocks and Visual C++.

Could you Please help me with this! :(


The Code:

#include<iostream>
using namespace std;
#include<math.h>
#include<conio.h>
#define stacksize 6
struct stacktype{
  float data[stacksize];
  int top;
};

void push( stacktype*s, float d){
  if ( s->top < 6) {
    s->data[s->top]=d;
    s->top++;
  }
}

float pop(stacktype*s){
  if ( s->top != 0){
    s->top--;
    return s->data[s->top];
  }
  return 0;
}

float oper(char symbol, float op1, float op2){
  switch (symbol){
    case '+': return (op1+op2);break;
    case '-':return (op1-op2);break;
    case '*':return (op1*op2);break;
    case '/':return (op1/op2);break;
    default: cout<<"illegal operation.......\n";
}

  return 0;
}

int main() {
  float op1,op2,symb,value;
  char symbol;
  stacktype *s;
  s= new stacktype;
  s->top=0;
  cout<<"Enter The Postfix Expression To Evaluate::  \n\n";
  cin>>symbol;
  while ( symbol != '.') {
   if ( symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/'){
   op2=pop(s);
   op1=pop(s);
   value=oper(symbol,op1,op2);
   push(s,value);
 }
 else {
   if ( symbol == '0') symb =0 ;
   else if ( symbol == '1') symb = 1;
   else if ( symbol == '2') symb =2 ;
   else if ( symbol == '3') symb =3 ;
   else if ( symbol == '4') symb = 4;
   else if ( symbol == '5') symb =5 ;
   else if ( symbol == '6') symb =6 ;
   else if ( symbol == '7') symb =7;
   else if ( symbol == '8') symb =8 ;
   else if ( symbol == '9') symb =9 ;

   push(s,symb);
  }
   cin>>symbol;
 }
 value=pop(s);
 cout<<"The Value:: \n"<<value<<endl;
 return 0;
}
Was it helpful?

Solution

Your code gives the correct result for me:

6
2
/
.
The Value:: 
3

Note that you are having inversed polish notation, i.e. the operand must follow after the values to operate on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top