'Why is the output 0 in one but the correct answer in the other? [duplicate]

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 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J.P.S.