Java 鸡兔同笼问题解法:代码示例与解析
public class ChickenRabbitPen { private int chickenCount; private int rabbitCount; private int totalCount;
public ChickenRabbitPen(int totalCount, int totalLegs) throws Exception {
if (totalLegs % 2 != 0) {
throw new Exception('总腿数必须为偶数');
}
this.totalCount = totalCount;
this.rabbitCount = (totalLegs - totalCount * 2) / 2;
this.chickenCount = totalCount - rabbitCount;
}
public int getChickenCount() {
return chickenCount;
}
public int getRabbitCount() {
return rabbitCount;
}
public static void main(String[] args) {
try {
ChickenRabbitPen pen = new ChickenRabbitPen(10, 28);
System.out.println('鸡的数量为:' + pen.getChickenCount());
System.out.println('兔的数量为:' + pen.getRabbitCount());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
原文地址: https://www.cveoy.top/t/topic/mZzn 著作权归作者所有。请勿转载和采集!