java完整代码100匹马拉100担货,一匹大马能驮3担货,一匹中马能驮2担货,两匹小马能驮1担货,求马各有多少只
时间: 2023-10-05 08:04:16 浏览: 250
以下是一个可能的 Java 代码实现:
```java
public class HorseAndLoad {
public static void main(String[] args) {
int totalHorses = 100;
int totalLoads = 100;
int bigHorseLoad = 3;
int middleHorseLoad = 2;
int smallHorseLoad = 1;
for (int bigHorse = 0; bigHorse <= totalHorses; bigHorse++) {
for (int middleHorse = 0; middleHorse <= totalHorses - bigHorse; middleHorse++) {
int smallHorse = totalHorses - bigHorse - middleHorse;
int totalLoadByHorses = bigHorse * bigHorseLoad + middleHorse * middleHorseLoad + smallHorse / 2;
if (totalLoadByHorses == totalLoads) {
System.out.printf("Big horses: %d, middle horses: %d, small horses: %d.%n", bigHorse, middleHorse, smallHorse);
}
}
}
}
}
```
这个程序使用了两个循环来枚举所有可能的马匹数量组合。对于每个组合,它计算所有马匹能够拉的货物总量,并检查它是否等于100。如果是,它就打印出这个组合。注意,由于两匹小马可以组成一匹中马,因此这里将小马数量除以2。
阅读全文