【问题标题】:Can't convert complex to float Error on Python无法在 Python 上将复杂转换为浮点错误
【发布时间】:2018-03-31 09:02:35
【问题描述】:

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

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 不是有效的三角形。两个较短的边不够长。这就像试图制作一个三角形,其中一边的长度为 1,第二边的长度为 3,第三边的长度为 1000。这显然不起作用。
  • 你能画出这样的三角形吗?
  • @ParasKumar:检查我的答案。如果有帮助,don't forget to accept it :)
  • @OliverCharlesworth 给我一些 4D 方格纸...

标签: python python-3.x area complex-numbers


【解决方案1】:

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

为确保您有有效的边,请在获取 a、b、c 的值后添加断言/验证:

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

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


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

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

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2021-10-10
  • 2017-03-20
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多