好的,所以当我测试这个时,它会给我一个错误,说明'指向'没有定义。我不知道如何解决这个问题,请问我能得到一些帮助吗? 附:代码还没有完全完成。我仍然需要打印其他点,但我想事先修复此错误。
第43行,主印(距离(点[0])+"" + 距离(points [1]))NameError:name' points'未定义
from math import *
def distance():
points = [(6, 5.7), (-9, 0)]
set1 = points[0]
set2 = points[1]
x1 = set1[0]
y1 = set1[1]
x2 = set2[0]
y2 = set2[1]
distance = sqrt((x1 - x2)**2 + (y1 + y2)**2)
return distance
def secondDistance():
points = [(0, 0), (4, 1)]
set1 = points[0]
set2 = points[1]
x1 = set1[0]
y1 = set1[1]
x2 = set2[0]
y2 = set2[1]
distance = sqrt((x1 - x2)**2 + (y1 + y2)**2)
return distance
def thirdDistance():
points = [(100, -100), (500, 300)]
set1 = points[0]
set2 = points[1]
x1 = set1[0]
y1 = set1[1]
x2 = set2[0]
y2 = set2[1]
distance = sqrt((x1 - x2)**2 + (y1 + y2)**2)
return distance
def main():
print("Original List")
print("Set 1 Set 2")
print(distance(points[0]) + " " + distance(points[1]))
print(distance())
print(secondDistance())
print(thirdDistance())
main()
答案 0 :(得分:0)
为什么你有三个功能可以做同样的事情?这完全违背了函数的目的:重用。试试这个:一个以点对作为参数的函数。列出主程序中的三个点,并遍历点列表。
from math import sqrt
def distance(points):
p1, p2 = points
print " points:", p1, p2
x1, y1 = p1
x2, y2 = p2
print " coords:", x1, y1, x2, y2
distance = sqrt((x1 - x2)**2 + (y1 + y2)**2)
return distance
point_list = [
[(6, 5.7), (-9, 0)],
[(0, 0), (4, 1)],
[(100, -100), (500, 300)]
]
for point_pair in point_list:
print distance(point_pair)
输出:
points: (6, 5.7000000000000002) (-9, 0)
coords: 6 5.7 -9 0
16.0464949444
points: (0, 0) (4, 1)
coords: 0 0 4 1
4.12310562562
points: (100, -100) (500, 300)
coords: 100 -100 500 300
447.2135955
答案 1 :(得分:0)
问题在于函数main
中没有名为points
的变量。在每个距离函数中,您定义一个名为points
的变量,但该变量在main
函数内部不可见。
此外,您应该注意,您的距离函数不会接受任何参数,因此即使在distance(points[0])
中定义了points
,main
也无法正常工作。
最后,这样的事情没有必要:
set1 = points[0]
x1 = set1[0]
您可以简单地写一下:
x1 = points[0][0]
您应该做的是重新组织代码,使distance
成为一个需要两个点的函数,并返回它们之间的距离。然后,在main
内,定义您希望获得距离的点,并在其上调用distance
:
from math import sqrt
def distance(point0, point1):
dx = point0[0] - point1[0]
dy = point0[1] - point1[1]
return sqrt(dx**2. + dy**2.)
def main():
p0 = (3., 5.)
p1 = (1., -2.)
d = distance(p0, p1)
print(d)
main()