物體的高度,以米為單位,在它被直接發射到空中 t 秒后,由公式 h = -4.9t^2 bt c 給出,其中 b 代表球的初始速度,以米/秒為單位,c 代表球的初始高度,以米為單位。使用 elif 陳述句,撰寫一個 Python 程式,顯示從球被拋出到落地的每一秒的高度。
設計您的程式以滿足以下標準: ? 用戶輸入初始速度和初始高度。? 輸出格式如下: 2 秒后,高度為 30.87 m。? 輸出表明球在地面上,而不是顯示負高度值。? 輸出不包含語法錯誤,例如“After 1 seconds,....”
我的代碼如下:
#initial values
t = 0
h = 0
#ask user for initial speed and initial height
b = float(input("What is the initial speed in metres per second?: "))
c = float(input("What is the initial height in metres: "))
#calculate and display height
while h>=0:
h = round(-4.9*t**2 b*t c, 2)
if t==1:
print("After 1 second, the height is", h, "m.")
elif h>0:
print("After", t, "seconds, the height is:", h, "m.")
else:
print("After", t,"seconds, the ball is on the ground")
t = t 1
代碼運行,但在用戶輸入初始速度和高度后,程式繼續運行并且不輸出任何內容。
uj5u.com熱心網友回復:
格式不好。所有這些 if 和 print 陳述句,以及 t 的增量,都必須縮進到 while 回圈內。
t = 0
h = 0
b = float(input("What is the initial speed in metres per second?: "))
c = float(input("What is the initial height in metres: "))
while h>=0:
h = round(-4.9*t**2 b*t c, 2)
if t==1:
print("After 1 second, the height is", h, "m.")
elif h>0:
print("After", t, "seconds, the height is:", h, "m.")
else:
print("After", t,"seconds, the ball is on the ground")
t = t 1
您應該使用像 PyCharm 這樣的 IDE 而不是單純的文本編輯器。
這是我得到的輸出。你的物理很簡單。他們似乎是正確的。
What is the initial speed in metres per second?: >? 0
What is the initial height in metres: >? 50
After 0 seconds, the height is: 50.0 m.
After 1 second, the height is 45.1 m.
After 2 seconds, the height is: 30.4 m.
After 3 seconds, the height is: 5.9 m.
After 4 seconds, the ball is on the ground
應該很容易計算出準確的影響時間。設定 h = 0 并求解時間。這是一個二次方程,所以應該有兩個根。拿一個有物理意義的——時間是一個真實的、正數。
uj5u.com熱心網友回復:
while h>=0:
h = round(-4.9*t**2 b*t c, 2)
代碼縮進的方式,這本身就是一個回圈,它永遠不會結束,因為h它總是 >= 0。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524661.html
標籤:Python数学
