首页 > 解决方案 > 使用 If 语句检查是否有错误发生

问题描述

我正在尝试编写一个程序来为我解决有关参数方程的问题。我正在尝试执行以下操作:

我试图找到参数方程的 2 个答案。第一个答案将是正平方根。第二个答案将是负平方根。如果第一个平方根引发数学域错误,则不要找到第二个答案。这是我到目前为止所拥有的:

def hitsGround(vertical_velocity, y_coordinate):
    h = vertical_velocity/-16/-2
    k = -16*(h)**2 + vertical_velocity*(h) + y_coordinate
    time = float(input("At what height do you want me to solve for time?: "))
    try:
        hits_height1 = math.sqrt((time - k)/-16) + h
    except ValueError:
        print("It won't reach this height.")
    else:
        print(f"It will take {hits_height1} seconds to hit said height.")

    try:
        hits_height2 = -math.sqrt((time - k)/16) + h
    except ValueError:
        print("There is no second time it will reach this height.")
    else:     
        print(f"It will take {hits_height2} seconds to hit said height.")

有什么方法可以使用 if 语句来检查第一个方程是否引发数学域错误,以便我可以使它找不到第二个答案?谢谢!

标签: pythonmathparametric-equations

解决方案


您不能使用if; 测试运行时异常。这正是try-except它的作用。但是,当直接定义非法操作时,您可以在尝试操作之前测试sqrt条件:

if (time - k)/-16 < 0:
    # no roots
else:
    # proceed to find roots.

推荐阅读