![](/img/trans.png)
[英]TypeError: 'float' object has no attribute '__getitem__'
[英]Python - TypeError: 'float' object has no attribute '__getitem__'
我在Python 2.7中运行了以下代码,但出现了错误。 为什么?
码:
def triangle_area(a, b, c):
"""
Returns the area of a triangle given the length of three sides
Code source: [here][1]
"""
def distance(p1, p2):
return math.hypot(p1[0]-p2[0], p1[1]-p2[1])
side_a = distance(a, b)
side_b = distance(b, c)
side_c = distance(c, a)
s = 0.5 * ( side_a + side_b + side_c)
return math.sqrt(s * (s - side_a) * (s - side_b) * (s - side_c))
运行以下命令:y = triangle_area(10.1,1.1,11.2)
产生此错误:回溯(最近一次呼叫最近):
[snip]
....in distance
return math.hypot(p1[0]-p2[0], p1[1]-p2[1])
TypeError: 'float' object has no attribute '__getitem__'
此代码段中的距离函数假定您将其传递给元组以表示点的(x,y)位置。
因此,要计算顶点为(0,0),(0,1),(1,1)的三角形的面积,您可以调用
triangle_area((0,0), (0,1), (1,1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.