请教百钱买百鸡问题
public class D{
public static void main(String[] args){
int rooster,hen,chick;
for(rooster=0;rooster <=20;rooster++){
for(hen=0;hen <=33;hen++){
for(chick=3;chick <=300;chick++){
if((rooster+hen+chick==100)&&((5*rooster+3*hen+chick/3)==100)){
System.out.print ( "rooster 's num: " + rooster+ "\t ");
System.out.print ( " hen 's num: " + hen+ "\t ");
System.out.println( " chick 's num: " + chick+ "\t ");
}
}
}
}
}
}
我的计算结果是
rooster 's num:0 hen 's num:25 chick 's num:75
rooster 's num:3 hen 's num:20 chick 's num:77
rooster 's num:4 hen 's num:18 chick 's num:78
rooster 's num:7 hen 's num:13 chick 's num:80
rooster 's num:8 hen 's num:11 chick 's num:81
rooster 's num:11 hen 's num:6 chick 's num:83
rooster 's num:12 hen 's num:4 chick 's num:84
想请问到底错在哪里了??
------解决方案--------------------把:if((rooster+hen+chick==100)&&((5*rooster+3*hen+chick/3)==100)){
改为:if((rooster+hen+chick==100)&&((5*rooster+3*hen+chick/3.0)==100.0)){
int 除以 int 的意思是整数,并不会产生小数的,将 3 改成 3.0 就可以了。
------解决方案--------------------把 for(chick=3;chick <=300;chick++){ 这个循环去掉,改成:
chick = 100 - rooster - hen;
以便加快速度。
------解决方案--------------------错在chick/3 因为chick/3是取整的,可以这样改:if((chick%3==0)&&(rooster+hen+chick==100)&&((5*rooster+3*hen+chick/3)==100))
------解决方案--------------------//优化代码
for(rooster=0;rooster <=100/5;rooster++){
for(hen=0;hen <=(100-rooster*5)/3;hen++){
{
chick=100-rooster-hen;
if(chick%3!=0)
continue;
if(rooster*5+hen*3+chick/3==100)
System.out.println(....);//略
}
------解决方案--------------------//修正下,附带加点注释
for (int rooster = 1; rooster <= 100 / 5; rooster++) {//
for (int hen = 1; hen <= (100 - rooster * 5) / 3; hen++) {//根据总价100
//尽量减少循环
int chick = (100 - 5 * rooster - 3 * hen) * 3;//根据总价计算
if (rooster + hen + chick != 100)//根据总数判断
continue;
System.out.println( "rooster= " + rooster + ",hen= " + hen
+ ",chick= " + chick);
}
}
------解决方案--------------------