C#遞歸思路的使用實(shí)例詳解
C#遞歸思路的使用在我們實(shí)際開(kāi)發(fā)中是十分重要的,C#遞歸思路的使用是我們高效開(kāi)發(fā)的一種模式,那么具體的實(shí)現(xiàn)實(shí)例的情況是什么呢?讓我們通過(guò)一個(gè)實(shí)例來(lái)了解。
C#遞歸思路題:關(guān)于牛生牛的問(wèn)題, 假設(shè)牛都是母牛;
有一個(gè)農(nóng)場(chǎng)有一頭成年母牛,每三個(gè)月后一頭小牛,小牛一年后長(zhǎng)大,長(zhǎng)大后每三個(gè)月又可以生一頭小牛,如些循環(huán),問(wèn)10年后農(nóng)場(chǎng)一共有多少牛?
C#遞歸思路實(shí)例開(kāi)發(fā):
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- namespace ConsoleApplication1
- {
- public class 牛
- {
- public int 月份;//當(dāng)月份>12且能整除3時(shí),生一頭小牛
- public string 出生日期;
- }
- class Program
- {
- static void Main(string[] args)
- {
- 牛 a = new 牛();
- a.月份 = 12;
- a.出生日期 = "牛祖先";
- ArrayList arr = new ArrayList();
- arr.Add(a);
- //開(kāi)始循環(huán),以月為單位循環(huán)
- for (int i = 1; i <= 12 * 10; i++)
- {
- //每個(gè)牛的年齡+1
- for (int j = 0; j < arr.Count; j++)
- {
- 牛 temp = (牛)arr[j];
- temp.月份++;
- if (temp.月份 >= 12 && temp.月份 % 3 == 0)
- {
- //生牛
- 牛 b = new 牛();
- b.月份 = -1;
- b.出生日期 = Convert.ToString(i / 12 + 1) +
- "年" + Convert.ToString(i % 12) + "月";
- arr.Add(b);
- }
- }
- }
- //C#遞歸思路
- //輸出牛的數(shù)量和每個(gè)牛的月份
- //foreach (object o in arr)
- //{
- //牛 temp = (牛)o;
- //Console.Write("年齡:{0}月\t",temp.月份);
- //Console.WriteLine("生日:{0}",temp.出生日期);
- //}
- Console.WriteLine("共計(jì){0}頭牛",arr.Count);
- }
- }
- }
C#遞歸思路的基本應(yīng)用情況就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#遞歸思路有所幫助。
【編輯推薦】