Search code examples
carea

Why is the output 0 in one but the correct answer in the other?


Suppose you have to find the area of a triangle when base and height are given

#include <stdio.h>
int main ()
{
    float base,height,area;
    printf("Enter base and height of triangle: \n");
    scanf("%f%f",&base,&height);
    area=0.5*base*height;
    printf("The area of the triangle is %f",area);
    return 0;
}

How come the program gives the right answer with the above code but not with the one below??

#include <stdio.h>
int main ()
{
    float base,height,area;
    printf("Enter base and height of triangle: \n");
    scanf("%f%f",&base,&height);
    area=(1/2)*base*height;
    printf("The area of the triangle is %f",area);
    return 0;
}

This one shows 0 regardless of what values you input. What obvious thing am I missing here?


Solution

  • The expression

    (1/2)

    divides two integers. In contrary to python or several other languages, this won't be implicitly cast to a float, but stays as integer. Hence, the result is 0.

    Changing the expression to

    (1./2)
    

    solves your problem.