2

I'm using this code to calculate the area of a triangle, with the values 2, 2 and 1. When I do the calculation in my pocket calculator I get 0.97, but in C# it's 0. I guess it has something to do about the rounding of the decimals, but I have changed the last value from i and up, but still get 0 as the result! What am I doing wrong? Help preciated! Thanks!

double i = (valueA + valueB + valueC) / 2;
return Math.Round(Math.Sqrt(i * (i - valueA) * (i - valueB) * (i - valueC)),1);
3D-kreativ
  • 9,053
  • 37
  • 102
  • 159

2 Answers2

8

Divide by 2.0 or 2d or 2D

Reason: Integer Division gives only integer part and removes the fraction part.

2 is integer. 2.0 is double value.

double i = (valueA + valueB + valueC) / 2.0;

OR

double i = (valueA + valueB + valueC) / 2d; 

OR

double i = (valueA + valueB + valueC) / 2D;

Second line remains the same

return Math.Round(Math.Sqrt(i * (i - valueA) * (i - valueB) * (i - valueC)),1);
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
2

Please try (valueA + valueB + valueC) / 2.0.

Jeffrey Zhao
  • 4,923
  • 4
  • 30
  • 52