I wrote a code for calculating Area of Triangle
a = float(input("Enter the first side of triangle: \n"))
b = float(input("Enter the second side of triangle: \n"))
c = float(input("Enter the thrid side of triangle: \n"))
s = (a+b+c) / 2
area = (s*(s-a) * (s-b) * (s-c)) ** 0.5
print("The area of triangle is %0.3f" %area)
My input values that I used were: 25, 4556, 5544
The error i received was:
print("The area of triangle is %0.3f" %area)
TypeError: can't convert complex to float
Can some body please help me with the problem? My code works fine when I input small numbers, like (5,6,7). Using Pycharm as my IDE.
The code doesn't work because the input sides do not form a triangle - 25 + 4556 < 5544
. As such, the term s-c
is negative, due to which computing the square root returns complex number.
To be sure you have valid sides, add an assertion/validation after you take the values for a, b, c which checks:
assert a+b+c > 2*max(a, b, c)
This basically ensures that sum of the two smaller sides is greater than the largest side.
As an aside, you can also validate that your sides are all positive:
assert all(x>0 for x in (a, b, c))