百鸡百钱===百马百担====for循环嵌套

package com.zuoye.test;
//百鸡百钱5文钱可以买一只公鸡,3文钱可以买一只母鸡,1文钱可以买3只雏鸡。
public class Baiji {
public static void main(String[] args)
{
int a;
int b;
int c;
int sum;
for(a=0;a<21;a++)
{
for(b=0;b<30;b++)
{
for(c=0;c<100;c++)
{
sum=5*a+3*b+c/3;
if(sum==100&&a+b+c==100)
{
System.out.println("公鸡"+a+"只,母鸡"+b+"只雏鸡"+c+"只");
}
}
}
}
}
}

 

 

 

百马百担:

package com.zuoye.test;
//百马百担,大马驮3担,中马驮2担,两只小马驮1担,问有大,中,小马各几匹
public class Baima {
public static void main(String[] args)
{
int a;
int b;
int c;
int sum;
for(a=0;a<100;a++)
{
for(b=0;b<100;b++)
{
for(c=0;c<100;c++)
{
sum=a*3+b*2+c/2;
if(a+b+c==100&&sum==100)
{
System.out.println("大马"+a+"只,中马"+b+"只小马"+c+"只");
}
}
}
}
}
}

  上面的没有考虑周全,改正后的:

package com.zuoye.test;
//百鸡百钱5文钱可以买一只公鸡,3文钱可以买一只母鸡,1文钱可以买3只雏鸡。
public class Baiji {
    public static void main(String[] args)
    {
        int a;
        int b;
        int c;
        int sum;
        for(a=0;a<21;a++)
        {
            for(b=0;b<30;b++)
            {
                for(c=0;c<100;c++)
                {
                    if(c%3==0)
                    {
                        sum=5*a+3*b+c/3;
                        if(sum==100&&a+b+c==100)
                        {
                            System.out.println("公鸡"+a+"只,母鸡"+b+"只雏鸡"+c+"");
                        }
                    }
                }
            }
        }    
    }
}

package com.zuoye.test;
//百马百担,大马驮3担,中马驮2担,两只小马驮1担,问有大,中,小马各几匹
public class Baima {
    public static void main(String[] args)
    {
        int a;
        int b;
        int c;        
        int sum;
        for(a=0;a<100;a++)
        {
            for(b=0;b<100;b++)
            {
                for(c=0;c<100;c++)
                {
                    if(c%2==0)
                    {
                        sum=a*3+b*2+c/2;
                        if(a+b+c==100&&sum==100)
                        {
                            System.out.println("大马"+a+"只,中马"+b+"只小马"+c+"");
                        }
                    }
                }
            }
        }
    }
}

 

 

posted @ 2016-09-12 22:22  丶疏影横斜  阅读(4207)  评论(2编辑  收藏  举报