利用Python语言编程,解决鸡兔同笼问题,已知同一个笼子里鸡和兔总共有h只,鸡和兔的脚数总共有f只,其中h和f需要用户输入,求鸡和兔各有多少只。
提示:利用循环,采用枚举法。
要求:当输入的h和f没有结果时,需要提示无解。
方法一:
while 1:
try:
h=int(input('请输入鸡和兔子共有多少只:'))
if h<=0 and h % 2 == 0:
print('请输入正数!')
continue
f=int(input('请输入鸡和兔子共有多少只脚:'))
if f<=0 and f % 2 == 0:
print('请输入正数!')
continue
break
except:
print('请输入正确的数字!')
def zph(h, f):
t=0
for r in range(1,h):
if t==1:
break
for c in range(1,h):
if c * 2 + r * 4 == f and c+r==h:
print("鸡%d只 兔%d只"%(c, r))
t=1
break
if t==0:
print('无解,请重新输入数据')
zph(h, f)
方法二:
while 1:
try:
h=int(input('请输入鸡和兔子共有多少只:'))
if h<=0 and h % 2 == 0:
print('请输入正数!')
continue
f=int(input('请输入鸡和兔子共有多少只脚:'))
if f<=0 and f % 2 == 0:
print('请输入正数!')
continue
break
except:
print('请输入正确的数字!')
t=0
for r in range(1,h):
c=h-r
if c * 2 + r * 4 == f:
print("鸡%d只 兔%d只"%(c, r))
t=1
if t==0:
print('无解,请重新输入数据')