1

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

我试图找到参数方程的 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 语句来检查第一个方程是否引发数学域错误,以便我可以使它找不到第二个答案?谢谢!

4

2 回答 2

0

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

if (time - k)/-16 < 0:
    # no roots
else:
    # proceed to find roots.
于 2020-05-15T00:25:26.100 回答
0

一般来说,使异常处理更容易的方法是做所有你需要做的事情来处理except. 例如,如果您不想在遇到第一个异常后找到第二个答案,只需return

    try:
        hits_height1 = math.sqrt((time - k)/-16) + h
    except ValueError:
        print("It won't reach this height.")
        return

    print(f"It will take {hits_height1} seconds to hit said height.")

如果您想让生活更轻松,只需允许引发异常(根本不捕获它),然后在调用函数中捕获它!

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?: "))

    hits_height1 = math.sqrt((time - k)/-16) + h
    print(f"It will take {hits_height1} seconds to hit said height.")

    hits_height2 = -math.sqrt((time - k)/16) + h
    print(f"It will take {hits_height2} seconds to hit said height.")

try:
    hitGround(1.0, 10.0)
except ValueError:
    print("It won't reach that height again.")

无论在哪里引发异常hitsGround,它都会立即停止该函数正在执行的任何操作,并且会except在调用范围内命中。这样你只需要一个try/except来涵盖这两种情况。

于 2020-05-15T00:37:24.647 回答