【问题标题】:Why is my program not comparing return values in an if, elif, else statement?为什么我的程序不比较 if、elif、else 语句中的返回值?
【发布时间】:2017-05-08 16:03:36
【问题描述】:

我遇到的问题是,即使点 M 比点 M 短于 P,反之亦然,程序只会打印它们的距离相同。这可能是我的返回值的问题吗?或使用 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()

【问题讨论】:

    标签: python if-statement return


    【解决方案1】:

    你需要使用你的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)
    

    【讨论】:

      【解决方案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 值。

      【讨论】:

        猜你喜欢
        • 2017-07-03
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 2012-05-11
        • 2014-05-13
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多