Search code examples
cpostfix-notationmathematical-expressions

different values on evaluating an expression in c in float and int representation?


on changing this expression to postfix representation and then evaluating it.. I'm getting 17.8 as answer.. if "n" would have been of float type then there is no problem in answer. since n is a variable of integer type, digits after decimal oint should be truncated and answer should be 17 but the output is 15. how?

#include<stdio.h>
int main()
{

int i=3,a=4,n;
float t =4.2;
n=a*a/i+i/2*t+2+t;
printf("n = %d\n",n);
return(0);
}

Solution

  • I'm getting 17.8 as answer.. if "n" would have been of float type then there is no problem in answer.

    No. You can't. You will get 17.833332 if your expression would be

    n=a*a*1.0/i+i/2.0*t+2+t;  
    

    See:

    a*a/i = (4*4)/3 = 16/3 = 5 
    i/2*t = (3/2)*4.2 = 1*4.2 = 4.2
    2 + t = 2 + 4.2 = 6.2  
    

    5 + 4.2 + 6.2 = 15.4 which will truncated to 15.