百雞百錢===百馬百擔====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+"");
                        }
                    }
                }
            }
        }
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM