用python程式設計 百錢買百雞
阿新 • • 發佈:2019-01-06
第一種方法是利用隨機數來判斷,可以得出花費100塊錢,買各種各樣總和為100只的雞
# author : momo ''' 百錢買百雞,現有100文錢,公雞5文錢一隻,母雞3文錢一隻, 小雞一文錢3只,要求:公雞,母雞,小雞都要有,把100文錢 買100只雞,買的雞是整數。多少隻公雞,多少隻母雞多少隻小雞? ''' import random a = True while a: a = 91 list1 = ['公雞', '母雞', '小雞'] gongji = 1 muji = 1 xiaoji = 3 while 0<=a<=91 : if random.choice(list1)=='公雞': gongji = gongji + 1 a = a - 5 elif random.choice(list1)=='母雞': muji = muji + 1 a = a - 3 elif random.choice(list1)=='小雞': xiaoji = xiaoji + 3 a = a - 1 if a==0: print("公雞有%d只,母雞有%d只,小雞有%d只,餘額=%d" % (gongji, muji, xiaoji, a)) a = False break else: continue
第二種方法是:只得出一種花費100塊錢來購買100只的雞的方法
for i in range(1,20):
for j in range(1,33):
for k in range(3,98,3):
if i+j+k==100 and 5*i + 3*j + k//3 ==100:
print("公雞:",i,"母雞:",j,"小雞:",k)