我该如何改进这一点,以便将距离添加到列表中,然后添加总和

2024-09-30 14:34:38 发布

您现在位置:Python中文网/ 问答频道 /正文

x1 = 0.00
y1 = 0.00

distList = [] 

def coord(x1, y1):
    while True:
        x2 = int(input("Enter x: ")) 
        y2 = int(input("Enter y: ")) 
        x1 = x2
        y1 = y2
        distance = ((x2 - x1)**2 + (y2 - y1)**2)**.5
        distList.append(distance)

def step():
    while True:

        if(x2 == 999 or y2==999):
            break
            print(sum(distList))
        else:
            coord(x1, y1)


coord(x1, y1)

我一直在努力找出如何打破循环一旦用户输入999,这并没有停止循环的某些原因和另一个问题是,列表distList是为了存储旅行的距离时,用户输入的x和y值,但它覆盖了第一次输入。你知道吗


Tags: 用户trueinputdefintdistancex1x2
1条回答
网友
1楼 · 发布于 2024-09-30 14:34:38

你被coord()函数的while循环“卡住”了:你从来没有调用过step(),所以你从来没有在while循环中遇到过if检查。你知道吗

您的coord()while循环中也没有任何条件(例如if),这意味着无法“跳出”该循环!你知道吗

看看这个稍微更新的代码:

x1 = 0.00
y1 = 0.00

distList = [] 

def coord(x1, y1):
    while True:
        x2 = int(input("Enter x: ")) 
        y2 = int(input("Enter y: ")) 

        # Let the user exit out here by submitting "999"
        if x2 == 999 or y2 == 999:
            break
        x1 = x2
        y1 = y2
        distance = ((x2 - x1)**2 + (y2 - y1)**2)**.5
        distList.append(distance)



coord(x1, y1)

在这段代码中我还可以看到一些其他问题;例如,如果设置x1=x2,那么x2-x1将始终为0。看看你是否能想出用x1 = x2行来解决这个问题!

相关问题 更多 >