ok this code gets three sides of a triangle and prints out the area... but it just prints out that the area is 0 every time... why?

#include <stdio.h>
#include <math.h>

double area(int a, int b, int c);
int main(int argc, char *argv[]){
  int a, b, c;

  printf("\nSide A: ");
  scanf("%d", &a);

  printf("\nSide B: ");
  scanf("%d", &b);

  printf("\nSide C: ");
  scanf("%d", &c);

  printf("\nThe area of the triangle is: %f\n", area(a, b, c));

  return(0);
}
double area( int a, int b, int c ){
  int s;
  double y;

  s = (a + b + c)/2;
  y = sqrt( s * (s - a)*(s - b)*(s - c) );

  return( y );
}

It doesn't always return zero. (Try 4, 5, 6.) But you should probably make at least s a double, and probably also a, b, and c.

Here are some points which might help...

1)The program is perfectly alright and is running without any changes in it (In windows).

2)While running it through command prompt or in a shell it might cause some problems(may be i dont know) because of your argc and argv (why not just say main(void) as you are not taking any input from command line.)

3)The formula for s is not for all lengths which come to your mind.It should form a triangle, only then can you expect an answer (Keep in mind the rule "SUM OF TWO SIDE OF A TRIANGLE SHOULD ALWAYS BE GREATER THAN THE THIRD SIDE"...it applies to all sides...)

ok this code gets three sides of a triangle and prints out the area... but it just prints out that the area is 0 every time... why?

Because you aren't using data types properly. When you say s = (a + b + c)/2; , it's integer = integer / integer . You lose information in a case where a+b+c is not an even number. Make s a double, and put a decimal point after 2 to make it a constant of the type double. s = (a + b + c)/2.;

3)The formula for s is not for all lengths which come to your mind.It should form a triangle, only then can you expect an answer (Keep in mind the rule "SUM OF TWO SIDE OF A TRIANGLE SHOULD ALWAYS BE GREATER THAN THE THIRD SIDE"...it applies to all sides...)

Each of the conditions a+b>c , a+c>b and b+c>a corresponds to one bracket in area = sqrt( s * (s - a)*(s - b)*(s - c) ) . If any of those conditions is not satisfied, one of the brackets will be zero or less, (a,b,c) will not be a triangle and the area will be undefined. Ie. the formula gives a correct answer in any case.
So, the only thing you need to do is to check whether the returned value is a positive number. If it's not, slap the user for wrong input.

Basically, you were getting 0 as output because s was calculated incorrectly, and the formula for area calculation saw that one of the sides equalled s (which gave you s-a = 0 -> area = 0)

This article has been dead for over six months. Start a new discussion instead.