C# for迴圈 迭代法 窮舉法應用

來源:互聯網
上載者:User

標籤:

迭代

 

 //兔子生兔子    

class Class5    

{        

static void Main(string[] args)      

   {           

    int tu1 = 1, tu2 = 1; //tu1是倒數第一個月的兔子數,tu2是倒數第二個月的兔子數         

    int tu=0;//要求的這個月的兔子數。

            for (int i = 3; i <= 24; i++)          

   {                 tu = tu1 + tu2;               

                      tu2 = tu1;            

                      tu1 = tu;                         

     }           

  Console.WriteLine(tu);      

   }   

  }

 

 

 //求年齡:有6個小孩子排在一起,問第一個多大年齡,他說比第二個小2歲,問第二個多大年齡,他說比第三個小2歲,以此類推,問第6個多大年齡,他說自己16歲。問第一個小孩子幾歲?
    class Class2
    {
        static void Main(string[] args)
        {
            int age = 16; //初始情況下,存的是第6個小孩子年齡,每次迴圈都會減2,分別代表第5,4,3,2,1個小孩子的年齡。
            for (int i = 5; i >= 1; i--)
            {
                age = age - 2;
            }
            Console.WriteLine(age);
        }
    }
}

 

  //猴子吃桃子。
    //公園裡有一隻猴子,和一堆桃子。猴子每天吃掉桃子數量的一半,把剩下的一半數量中扔掉一個壞的。到了第7天猴了睜開眼發現只剩下一個桃子了,問原來有多。
    //190
    class Class4
    {
        static void Main(string[] args)
        {
            int count = 1;
            for(int i=6;i>=1;i--)
            {
                count = (count + 1) * 2;
            }
            Console.WriteLine(count);
        }
    }
}

 

 

窮舉

2.有三種硬幣若干:1分,2分,5分。要組合1毛5,有哪些組合方式?

 

static void Main(string[] args)
        {
            for(int a=0;a<=15;a++) //a代表1分的硬幣個數
            {
                for(int b=0;b<=7;b++)//b代表2分的硬幣個數
                {
                    for(int c=0;c<=3;c++)//c代表5分硬幣的個數
                    {
                        if(a*1+b*2+c*5 == 15)
                        {
                            Console.WriteLine("1分硬幣需要"+a+"個,2分的硬幣需要"+b+"個,5分的硬幣需要"+c+"個");
                        }
                    }
                }
            }
        }
    }
}

C# for迴圈 迭代法 窮舉法應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.