iT邦幫忙

0

Python 迴圈練習

問題如下:
Statement
As a future athlete you just started your practice for an upcoming event. Given that on the first day you run x miles, and by the event you must be able to run y miles.
Calculate the number of days required for you to finally reach the required distance for the event, if you increases your distance each day by 10% from the previous day.

Print one integer representing the number of days to reach the required distance.
大意是 第一天我可以一次跑 x miles
訓練的最後一天 我的目標是一次跑 y miles
每訓練一天 我可以比前一天 多跑10%

要達到目標 我需要訓練幾天?

以下是我練習的語法

a = int(input()) --第一天可以跑得miles
b = int(input()) --最後一天目標miles
ans = 0 --紀錄每一天可以跑得miles
i = 1 --從第一天開始
while ans <= b:
    ans = a * 1.1
    i += 1
print(i) --印出總共訓練了幾天

測試資料 a = 10 b = 20
snakify練習網址

按下 執行後
整個網頁會當機 沒有回應
不知道是不是我寫了無窮迴圈導致的
還是這個練習網站本身的問題??
(PS 需要註冊後才可以練習題目)

更新正解:

a = int(input()) 
b = int(input()) 
ans = 0 
i =  1
if(a < b):
    while ans < b:
        ans = a * 1.1
        i += 1
        a = ans
print(i)

更新簡化:

a = int(input()) 
b = int(input()) 
i =  1
if(a < b):
    while a < b:
        a *= 1.1
        i += 1
print(i) 
看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2020-02-20 10:57:19 檢舉
本機上跑一跑不就知道是不是無窮迴圈了?
永遠都是 a*1.1 XD
然後你只要加到 a=b的天數那 while應該是 ans<b
摩摩楓 iT邦新手 4 級 ‧ 2020-02-20 11:08:07 檢舉
應該在 i += 1的下一行 加上
a = ans
這樣才符合每天進步10%的規則。
Zed_Yang iT邦新手 3 級 ‧ 2020-02-20 11:31:21 檢舉
笨了2天...感謝各位回覆
while a <b:
a+= a*0.1
i+=1
這樣就可以了
Zed_Yang iT邦新手 3 級 ‧ 2020-02-20 11:47:11 檢舉
感謝樓上
突然想起python可以這樣
while a <b:
a *= 1.1
i+=1

a *= 1.1 等於 a = a*1.1
在做迴圈練習的時候可以自己設定一個 limit 跟 count 變數(叫什麼名字都可以)
迴圈裡面就每次都 count += 1 ,每次都檢查 count 超過 limit 了沒,超過就直接跳出迴圈
limit 設個一萬十萬都可以,看跑多複雜的內容自己評估一下,反正要有停下來的條件 ..
Zed_Yang iT邦新手 3 級 ‧ 2020-02-21 13:37:52 檢舉
等於是自己再額外設定個例外處理的條件
以防止無窮迴圈的情況

感謝
學了一課
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
mlck970677
iT邦新手 5 級 ‧ 2020-02-20 10:57:12
最佳解答

你的邏輯錯了啊!

ans = a * 1.1

你想看看你a是10,乘1.1倍後等於結果1.1a,第二次迴圈a再乘1.1倍等於結果1.1a...
要什麼時候才會等於b?(可能要等到我有個像nezuko一樣可愛的妹妹的時候吧/images/emoticon/emoticon02.gif

nezuko ~<3

叫我妹妹的名字做啥?/images/emoticon/emoticon09.gif(誤

我要發表回答

立即登入回答