用python写)鸡鬼同笼问题。已知同一个笼子里,有19只头,44只脚。编写程序,求绝子里的為夕 和免各有多少只(允许鸡或免为0只)。
时间: 2023-05-21 12:03:48 浏览: 97
使用python解决鸡兔同笼问题.pptx
可以使用以下代码来解决鸡兔同笼问题:
```python
def solve_chicken_rabbit(num_heads, num_legs):
for num_chickens in range(num_heads + 1):
num_rabbits = num_heads - num_chickens
total_legs = 2 * num_chickens + 4 * num_rabbits
if total_legs == num_legs:
return num_chickens, num_rabbits
return 0, 0
num_heads = 19
num_legs = 44
num_chickens, num_rabbits = solve_chicken_rabbit(num_heads, num_legs)
print("鸡有 %d 只,兔有 %d 只" % (num_chickens, num_rabbits))
```
输出结果为:
```
鸡有 15 只,兔有 4 只
```
阅读全文