-1

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?

students
  • 51
  • 8
  • 5
    The second one computes 1/2 as integer, which is always 0. – J.P.S. Mar 21 '22 at 13:46
  • 1
    In C, "/" operator returns only the integer part of the division, hence the formula for the area becomes 0 * base * height. – kmalarski Mar 21 '22 at 13:47
  • 2
    try something like `1.0f/2` or `1/2.0f` to tell the compiler you want floating point division there. – yano Mar 21 '22 at 13:48
  • Neither is correct. Binary `*` has left-to-right associativity so in case of `0.5*base*height` the whole expression will be evaluated as `double`. – Lundin Mar 21 '22 at 13:51
  • @kmalarski trying to typecast it wont work either? – students Mar 21 '22 at 14:04
  • @Lundin sorry, I don't know what that means, could you explain a bit more please? – students Mar 21 '22 at 14:05
  • 1
    It means that if you use `float` types you should always use floating point constants ending with an `f`. That is: `0.5f`. Otherwise you might as well use `double` everywhere (which is probably the correct choice anyway, if programming for a PC). – Lundin Mar 21 '22 at 14:11
  • @Lundin ahh alright, thank you for explaining – students Mar 22 '22 at 08:40

1 Answers1

2

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.

J.P.S.
  • 485
  • 4
  • 11