百鸡问题java代码
时间: 2023-07-29 10:06:06 浏览: 137
以下是百鸡问题的Java代码实现:
```java
public class HundredChickens {
public static void main(String[] args) {
int totalMoney = 100;
int totalChickens = 100;
int cockPrice = 5;
int henPrice = 3;
int chickPrice = 1 / 3;
int cockNumber, henNumber, chickNumber;
for (cockNumber = 0; cockNumber <= totalMoney / cockPrice; cockNumber++) {
for (henNumber = 0; henNumber <= totalMoney / henPrice; henNumber++) {
chickNumber = totalChickens - cockNumber - henNumber;
if (chickNumber % 3 == 0 && cockNumber * cockPrice + henNumber * henPrice + chickNumber * chickPrice == totalMoney) {
System.out.println("公鸡数量:" + cockNumber + ",母鸡数量:" + henNumber + ",小鸡数量:" + chickNumber);
}
}
}
}
}
```
该代码使用了两层循环来遍历公鸡和母鸡的可能数量,然后通过计算小鸡的数量来判断是否符合题目要求。最终输出符合要求的结果。
阅读全文