为什么以下代码给出的答案与解析答案相差甚远?

时间:2021-04-27 19:47:33

标签: python python-3.x

我正在尝试学习 Python,但遇到了以下问题:

"一个球从高度为 h 的悬崖上直接落下。时间 t 后球的位置 可以表示为:

y(t) = v0*t − (at^2)/2 + h

其中 a 是加速度(以 m/s^2 为单位),v0 是球的初始速度(以 m/s 为单位)。 我们希望找到球经过某个高度 h1 需要多长时间 t1。换句话说, 我们希望找到 t1 的值,使得 y(t1) = h1。每个 delta_t 测量球的位置 秒。 编写一个程序,通过以下方式找出球到达高度 h1 所需的时间 t1 使用while循环。在这里,我们让 h = 10m,y1 = 5m,delta_t = 0.01 s,v0 = 0m/s 和 a = 9.81m/s^2。"

我用 Python 编写了以下代码。问题是我得到的答案与我在纸上解决问题时所期望的答案不同(对于 y1 = 5m,t = 1.01s,对于 y1 = 3.6m,t = 1.14s)。我不确定问题到底出在哪里。这是我的代码:

import math
import numpy as np

h = 10
y1 = float(input("Enter the height you want:"))
delta = 0.01
t = v_i = 0
a = 9.81

y = v_i * t - (a * pow(t, 2)/2) + h


while True:
    if y <= y1:
        print("The object will be at height",format(y, "0.3") ,y1, "around the time", format(t, ".3"), "s")
        break
    else:
        t += delta
        h = y
        v_i = v_i - a*t
        y = v_i * t - (a * pow(t, 2)/2) + h

1 个答案:

答案 0 :(得分:2)

您似乎想要得出一个时间 <script> function Get(yourUrl){ var Httpreq = new XMLHttpRequest(); // a new request Httpreq.open("GET",yourUrl,false); Httpreq.send(null); return Httpreq.responseText; } var div = document.getElementById('myImg'); var json = JSON.parse(Get("https://nekos.life/api/v2/img/meow")); div.innerHTML = "<img src='"+json.url+"'/>"; </script> ,其距离与用户要求的相同。

为此,您尝试制作一个循环,猜测时间 t

犯了错误。

它比你想象的更简单:

t

请注意,您的 h = 10 y1 = float(input("Enter the height you want:")) delta = 0.01 t = 0 a = 9.81 y = h # y starts at the top of the cliff while y > y1: t += delta # time t is still guessed here y = h - (a * pow(t, 2)/2) # Just recalculate y for the new time t print(f"The object will be at height {y1} around the time {t}") 可以始终假定为 v_i

相关问题