为什么我的程序不比较if、elif和else语句中的返回值?

2024-09-27 07:28:29 发布

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

我遇到的问题是,即使点M比点M短,或者相反,程序也只打印它们的距离相同。这可能是我的返回值有问题吗?还是用if,elif,else语句

import math
print("This Program takes the coordinates of two points (Point M and N) and uses the distance formula to find which "
      "point is closer to Point P (-1, 2).")

x_P = -1
y_P = 2

def main():
    x_1 = int(input("Enter an x coordinate for the first point: "))
    y_1 = int(input("Enter an x coordinate for the first point: "))
    x_2 = int(input("Enter an x coordinate for the second point: "))
    y_2 = int(input("Enter an x coordinate for the second point: "))
    distance(x_1, y_1, x_2, y_2)
    distance1 = 0
    distance2 = 0
    if distance1 < distance2:
        print("Point M is closer to Point P.")
    elif distance1 > distance2:
        print("Point N is closer to Point P.")
    else:
        print("Points M and N are the same distance from Point P.")


def distance(x_1, y_1, x_2, y_2):
    distance1 = math.sqrt((x_P - x_1) ** 2 + (y_P - y_1) ** 2)
    distance2 = math.sqrt((x_P - x_2) ** 2 + (y_P - y_2) ** 2)
    return distance1, distance2


main()

Tags: thetoancoordinateforinputmathint
2条回答

您需要使用return值,因此

distance(x_1, y_1, x_2, y_2)
distance1 = 0
distance2 = 0

你应该使用

distance1, distance2 = distance(x_1, y_1, x_2, y_2)
distance(x_1, y_1, x_2, y_2)
distance1 = 0
distance2 = 0

对distance()的调用没有任何可应用返回值的内容,因此它们基本上消失了。distance()函数中的distance1和distance2是函数本身命名空间的本地值。即使它们不是,您也会用distance1=0和distance2=0语句覆盖它们

简易修复:

(distance1, distance2) = distance(x_1, y_1, x_2, y_2)

因为您的函数返回一个元组,所以只需在主命名空间中接受包含变量的元组即可

哦,所有的输入都要求x值

相关问题 更多 >

    热门问题