1. Python 使用 PuLP 库
```python
from pulp import *
创建问题实例
problem = LpProblem("鸡兔同笼", LpMinimize)
定义决策变量
chickens = LpVariable("鸡", lowBound=0, cat=LpInteger)
rabbits = LpVariable("兔", lowBound=0, cat=LpInteger)
添加目标函数(这里随便写个,因为只是求解鸡和兔的数量)
problem += 0
添加约束条件
problem += chickens + rabbits == 35 头的数量
problem += 2 * chickens + 4 * rabbits == 94 脚的数量
求解
problem.solve()
输出结果
print(f"鸡: {value(chickens)}")
print(f"兔: {value(rabbits)}")
```
2. Python 递归方法
```python
def solve_chicken_rabbit(total_count, total_legs):
for chicken_count in range(total_count + 1):
rabbit_count = total_count - chicken_count
if (chicken_count * 2 + rabbit_count * 4) == total_legs:
return chicken_count, rabbit_count
return None
def main():
total_count = 35
total_legs = 94
result = solve_chicken_rabbit(total_count, total_legs)
if result:
chicken_count, rabbit_count = result
print("鸡的数量:", chicken_count)
print("兔的数量:", rabbit_count)
else:
print("无解")
if __name__ == "__main__":
main()
```
3. Python 循环方法
```python
def solve_chicken_rabbit(total_count, total_legs):
for chicken_count in range(total_count + 1):
rabbit_count = total_count - chicken_count
if (chicken_count * 2 + rabbit_count * 4) == total_legs:
return chicken_count, rabbit_count
return None
def main():
total_count = 35
total_legs = 94
result = solve_chicken_rabbit(total_count, total_legs)
if result:
chicken_count, rabbit_count = result
print("鸡的数量:", chicken_count)
print("兔的数量:", rabbit_count)
else:
print("无解")
if __name__ == "__main__":
main()
```
4. C 语言
```c
include
int main() {
int head, foot, chicken, rabbit;
printf("请输入头的总数和脚的总数: ");
scanf("%d %d", &head, &foot);
rabbit = (foot - 2 * head) / 2;
chicken = head - rabbit;
if (rabbit >= 0 && chicken >= 0 && foot == 4 * chicken + 2 * rabbit) {
printf("鸡的数量为:%d, 兔的数量为:%d\n", chicken, rabbit);
} else {
printf("无解\n");
}
return 0;
}
```
5. Java
```java
public class ChickenRabbitInCage {
public static void main(String[] args) {
int heads = 35; // 头的总数
int legs = 94; // 脚的总数
int chicken, rabbit;
rabbit = (legs - 2 * heads) / 2;
chicken = heads - rabbit;
System.out.println("鸡的数量:" + chicken);
System.out.println("兔的数量:" + rabbit);
}
}
```
这些代码示例展示了如何使用不同编程语言解决鸡兔同笼问题。你可以选择最适合你的编程语言和方法来实现。