# 鸡兔同笼问题
# 将鸡和兔子关在同一个笼子里,已知头有xx个,脚有xx只,求有几只兔子和几只鸡
def caculate_num(head: int, foot: int):
rabbit = (foot - head * 2) // 2
chicken = head - rabbit
temp_leg_num = rabbit * 4 + chicken * 2
if temp_leg_num == foot and rabbit >= 0 and chicken >= 0:
return True, rabbit, chicken
else:
return False, 0, 0
while True:
while True:
head_ins = input('请输入头的数量:')
if head_ins.isdigit():
head_num = int(head_ins)
break
else:
print('请检查输入数据,重新输入')
while True:
foot_ins = input('请输入脚的数量:')
if foot_ins.isdigit():
foot_num = int(foot_ins)
break
else:
print('请检查输入数据,重新输入')
status, rabbit, chicken = caculate_num(head_num, foot_num)
if status:
print('{}个头,{}只腿,计算得出鸡有{}只,兔子有{}只'.format(head_num, foot_num, chicken, rabbit))
else:
print('经过检查{}个头,{}只腿的数量,不符合四腿兔子两腿鸡的设定,请重新输入'.format(head_num, foot_num))
输出结果
请输入脚的数量:250
100个头,250只腿,计算得出鸡有75只,兔子有25只