python while-loop的瓶蓋兌換問題?

2021-04-03 9:33 pm
題目:
有一活動可以用4個瓶蓋換一個全新的飲料,在某人已經有N個瓶蓋的情況下,某人可以跟朋友借一個瓶蓋為前提的,試問某人總共可以喝到多少瓶飲料?

初步想法就是計算商數跟餘數,但是就不知道要怎麼打跟while有關的程式碼了,因此想請問一下大家

回答 (2)

2021-04-04 9:56 am
# !/usr/bin/env python3
#

caps = int(input("已經有?個瓶蓋: "))
loan = int(input("可以跟朋友借?個瓶蓋: "))
exch = int(input("用?個瓶蓋換一個全新的飲料: "))
bott = 0

while (caps + loan) >= exch :
  if caps >= exch:
    temp = caps // exch
    caps = caps % exch + temp
    print('用{0}個瓶蓋換{1}個全新的飲料 剩餘{3}瓶蓋'.format(temp*exch, temp, loan, caps))
    bott += temp
  else:
    temp = (caps + loan) // exch
    if (temp + (caps+loan) - (temp * exch)) < loan: break
    bott = bott +temp
    caps = caps - ((temp * exch) - temp)
    print('借{2}個瓶蓋,用{0}個瓶蓋換{1}瓶全新的飲料 龜環{2} 剩餘{3}瓶蓋'.format(temp*exch,temp, loan, caps))

print ('done - 總共可以喝到{0}瓶 共換{1}瓶蓋, 餘{2}瓶蓋.'.format(bott,bott*exch,caps))
2021-04-03 11:39 pm
以下提供有借有還的解法

def main():
    drinks=0
    caps=int(input("caps number:"))
    exch=int(input("exchange number:"))
    while caps>=exch:
        new=caps//exch
        old=caps%exch
        caps=new+old
        drinks+=new #drinks=drinks+new
    if caps==(exch-1):
        drinks+=1 #drinks=drinks+1
        caps=0
    print("new drinks:",drinks)

if __name__=="__main__":
    main()


收錄日期: 2021-04-11 23:33:41
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20210403133304AAgXpSA

檢視 Wayback Machine 備份