簡體   English   中英

初學者Python數學障礙

[英]Beginner Python math road-block

問題:開車旅行時,我經常注意到指示到某個城市或城鎮的英里數,想知道我要多久才能到達那里。 生成可以接受我的速度和行進距離的代碼,並指出到達目的地需要多長時間(以分鍾為單位)。 (請記住,MPH告訴我60分鍾內可以行駛多少英里。)

這是我到目前為止產生的代碼。 我認為問題出在第5或第6行,但我感到困惑。 我可以輸入我的MPH(70)和我的距離(120)。 我的答案應該是102.857 .....但不會計算。

answer1 = input("Please enter the speed you will be traveling in MPH: ")
mph = int(answer1)
answer2 = input("Please enter the distance you will be traveling: ")
distance = int(answer2)
time = float((answer2 / answer1) * answer1)
print("That will take " +str(time) + " minutes.")

您的代碼存在一些問題,即嘗試將字符串和整數相除,並使用錯誤的公式進行時間計算。 這是已修復問題的代碼。

answer1 = input("Please enter the speed you will be traveling in MPH: ")
mph = float(answer1)
answer2 = input("Please enter the distance you will be traveling: ")
distance = float(answer2)
time = float((distance / mph) * 60)
print("That will take " +str(time) + " minutes.")

輸出:

Please enter the speed you will be traveling in MPH: 70
Please enter the distance you will be traveling: 120
That will take 102.85714285714285 minutes.

當您從終端讀取輸入時,它將作為字符串讀取。 您正在將answer1answer2轉換為int並將它們分別存儲為mphdistance但是使用原始字符串進行計算。 在第五行使用以下代碼。

time = float((distance / mph) * mph)

這是python問題。 用int划分時。 它可能會給您錯誤的結果。 請確保您的每個輸入均為浮點型。 它將幫助您獲得所需的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM