Floating point division in Stacks

This is a postfix evaluation program but the division is returning the int form of the answer instead of the float.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    #include <iostream>
#include <cstdlib>
#include <fstream>
#include <cmath>
#define MAXLEN 30;
using namespace std;

struct Stack{
    int top;
    int num;
    float element[30];
};

Stack *initStack(){
    Stack *s=(Stack *)malloc(sizeof(Stack));
    s->top=-1;
}

bool isEmpty(Stack *s){
    return (s->top==-1);
}

int peek(Stack *s){
    if(isEmpty(s)){
        cout<<"Empty"<<endl;
    }
    return s->element[s->top];
}

void push(Stack *s, int n){
    s->top=s->top+1;
    s->element[s->top]=n;
}

float pop(Stack *s){
    float c;
    if(isEmpty(s)){
        cout<<"empty"<<endl;
    }else{
        c=((float)s->element[s->top]);
        s->top=s->top-1;
        return c;
    }
}

int evaluate(string exp){
    int j;
    float a;
    float b;
    float c;
    Stack *temp;
    Stack *s = initStack();
    for (j = 0; j < exp.length(); j++) {
        if (exp[j]>='0' && exp[j]<='9') {
            push(s, exp[j] - '0');
        }
        else {
            a = pop(s);
            b = pop(s);
            if (exp[j] == '+')
                c = b + a;
            else if (exp[j] == '-')
                c = b - a;
            else if (exp[j] == '*')
                c = b * a;
            else if (exp[j] == '/')
                c = (float(b / a));
            else if (exp[j] == '^')
                c = pow(b, a);
            //temp->num = c;
            push(s, c);
        }
    }
return pop(s);
}


int main(){
    //cout<<((float)5/2)<<endl;
	cout<<"Evaluation: "<<evaluate("52/")<<endl;

return 0;
}


Last edited on
Line 71:
 
push(s,c)


Line 30:
 
void push(Stack *s, int n){


I think you see the problem.
omg, I have been up and down this code and I completely missed that.
Thanks for the eagle eye but I'm still getting the same problem after the change
Line 46:
 
int evaluate(string exp){

Once again, you need to return a float, not int.
Since you are only using floats, you should really get scrutinize everywhere you use an int and make sure that you really want an int there instead of a float. You have the same problem in the peek() function as well.
Last edited on
Thanks a lot. I thought I wasn't understanding the syntax but it was just simple absent mindedness.
Topic archived. No new replies allowed.