Python 上无法将复数转换为浮点数错误

Can't convert complex to float Error on Python

我写了一个计算三角形面积的代码

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)

我使用的输入值是:25、4556、5544

我收到的错误是:

print("The area of triangle is %0.3f" %area)
TypeError: can't convert complex to float

有人可以帮我解决这个问题吗?当我输入小数字时,我的代码工作正常,比如 (5,6,7)。使用 Pycharm 作为我的 IDE.

代码不起作用,因为输入边没有形成三角形 - 25 + 4556 < 5544。因此,术语 s-c 是负数,因此计算平方根 returns 复数。

为确保你有有效的边,在你取 a、b、c 的值后添加一个 assertion/validation 检查:

assert a+b+c > 2*max(a, b, c)

这基本上保证了两个较小边的总和大于最大边。


顺便说一句,你也可以验证你的双方都是积极的:

assert all(x>0 for x in (a, b, c))