# Calculate the Area of a Triangle

Calculate the Area of a Triangle

a = float(input(‘Input the length of the first side:’))

b = float(input(‘Input the length of the second side:’))

c = float(input(‘Input the length of the third side:’))

# Calculate the semiperimeter

s = (a + b + c) / 2

# Calculate the area

area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

print(‘The area of the triangle is {0:0.2f}’.format(area))

The output obtained after executing the preceding code is as follows:

Input the length of the first side: 5

Input the length of the second side: 6

Input the length of the third side: 7

The area of the triangle is 14.70

If you enter the lengths of the first, second, and third sides as 2, 2, and 4, the output is 0. Why?

The Triangle Inequality Theorem states that for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side. Therefore, the lengths you enter are invalid, and the result obtained based on Heron’s formula is 0.  In this case, you can modify your code as follows:

a = float(input(‘Input the length of the first side:’))

b = float(input(‘Input the length of the second side:’))

c = float(input(‘Input the length of the third side:’))

#Determine whether the three side can form a triangle. If yes, Heron’s formula is used to calculate the area and the result is output; if no, the result states that the three sides can’t form a triangle.

if (a+b>c) and (a+c>b) and (b+c>a):

# Calculate the semiperimeter

s = (a + b + c) / 2

# Calculate the area

area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

print(‘The area of the triangle is {0:0.2f}’.format(area))

else:

print(‘The three sides cannot form a triangle.’)

After being modified, the program displays a message indicating that the three sides can’t form a triangle if you enter the invalid side lengths.

Provided by @余宇宙-清远