@TOC
Java双重嵌套for循环实现百钱买百鸡的写法(一)
//定义一个记录循环次数变量
int count = 0;
for(int chk = 1; chk <= 100 / 5; ++chk) {
for(int hen = 1; hen <= 100 / 3; hen++) {
int chilk = 100 - hen - chk;
if(chilk + hen + chk == 100 && chilk / 3 + hen * 3 + chk * 5 == 100 && chilk % 3 == 0) {
count++;
System.out.println("第"+count+"可能:");
System.out.println("鸡翁:"+chk+"只\t"+"鸡母:"+hen+"只\t"+"鸡雏:"+chilk+"只\t");
}
}
}
System.out.println("一共有"+count+"可能");
执行结果:
Java三重嵌套for循环实现百钱买百鸡的写法(二)
for(int chk = 1; chk <= 100 / 5; ++chk) {
for(int hen = 1; hen <= 100 / 3; hen++) {
for(int chilk = 3; chilk <= 99; chilk += 3) {
if(chilk / 3 + hen * 3 + chk * 5 == 100) {
if(chilk + hen +chk == 100 ) {
System.out.println("鸡翁:"+chk+"只\t"+"鸡母:"+hen+"只\t"+"鸡雏:"+chilk+"只\t");
}
}
}
}
}
执行结果如下: