C#遞歸思路的使用實例詳解
作者:佚名
C#遞歸的使用是我們在處理程序設計時經常會碰到的問題,那么具體的實現是怎么樣的呢?那么本文就向你詳細介紹C#遞歸的相關應用。
C#遞歸思路的使用在我們實際開發中是十分重要的,C#遞歸思路的使用是我們高效開發的一種模式,那么具體的實現實例的情況是什么呢?讓我們通過一個實例來了解。
C#遞歸思路題:關于牛生牛的問題, 假設牛都是母牛;
有一個農場有一頭成年母牛,每三個月后一頭小牛,小牛一年后長大,長大后每三個月又可以生一頭小牛,如些循環,問10年后農場一共有多少牛?
C#遞歸思路實例開發:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- namespace ConsoleApplication1
- {
- public class 牛
- {
- public int 月份;//當月份>12且能整除3時,生一頭小牛
- public string 出生日期;
- }
- class Program
- {
- static void Main(string[] args)
- {
- 牛 a = new 牛();
- a.月份 = 12;
- a.出生日期 = "牛祖先";
- ArrayList arr = new ArrayList();
- arr.Add(a);
- //開始循環,以月為單位循環
- for (int i = 1; i <= 12 * 10; i++)
- {
- //每個牛的年齡+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#遞歸思路
- //輸出牛的數量和每個牛的月份
- //foreach (object o in arr)
- //{
- //牛 temp = (牛)o;
- //Console.Write("年齡:{0}月\t",temp.月份);
- //Console.WriteLine("生日:{0}",temp.出生日期);
- //}
- Console.WriteLine("共計{0}頭牛",arr.Count);
- }
- }
- }
C#遞歸思路的基本應用情況就向你介紹到這里,希望對你了解和學習C#遞歸思路有所幫助。
【編輯推薦】
責任編輯:仲衡
來源:
百度知道