/* (程序头部注释开始) * 程序的版权和版本声明部分 * Copyright (c) 2011, 烟台大学计算机学院学生 * All rights reserved. * 文件名称:一列数规则如下:1,1,2,3,5,8,13,21,34...求第30位数是多少?(用递归算法实现) * 作 者: 雷恒鑫 * 完成日期: 2012 年 09 月 09 日 * 版 本 号: V1.0 * 对任务及求解方法的描述部分 * 输入描述: * 问题描述: * 程序输出: * 程序头部的注释结束 */ [csharp] <span style="font-size:24px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication_do_while { class Program { static void Main(string[] args) { Console.WriteLine("这是一个“一列数规则如下:1,1,2,3,5,8,13,21,34...求第30位数是多少?”的程序"); Console.Write("请问您想求第几位数?"); int number = int.Parse(Console.ReadLine()); int m = f(number);//递归函数 Console.WriteLine("第{0}位数为:{1}", number, m); Console.ReadKey(); } static int f(int number)//递归就是在过程或函数里调用自身。 { int fact; if (number == 0 || number == 1)//使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。 { if (number == 0)//当number等于2是有0这种情况出现 { fact = 0; } else { fact = 1; } } else { fact = f(number - 1) + f(number - 2); } return fact; } } } </span>
运行结果:
  
经验积累: 1. 递归是计算机科学中的一种重要方法。 能采用递归描述的算法通常有这样的特征:为求解规模为N的问题,设法将它分解成规模较小的问题,然后从这些小问题的解方便地构造出大问题的解,并且这些规模较小的问题也能采用同样的分解和综合方法,分解成规模更小的问题,并从这些更小问题的解构造出规模较大问题的解。特别地,当规模N=1时,能直接得解。
|