C#递归函数应用实例解析

开发 后端
C#递归函数应用实例主要向你介绍了使用递归函数来实现的一个例子,希望这些对你了解和学习C#递归函数有所帮助。

关于C#递归函数的应用问题一直是编程人员容易想到的解决办法,C#递归函数的应用理解是什么呢?那么以下是一个实例应用,用来查找一个int数组中最大的值在屏幕中打印出来。

第一种做法,调用Math.Max的方法来比较大小。

  1. using System;  
  2.  
  3. class Program  
  4.  
  5. {  
  6. static void Main()  
  7.  
  8. {  
  9.  
  10. int[] a = { 1, 210, 3, -51, 327, -58, 102300, 54343, -20, 0 };  
  11.  
  12. int max = FindMax(a, a.Length);  
  13.  
  14. Console.WriteLine("最大值: {0}", max);  
  15.  
  16. }  
  17.  
  18. static int FindMax(int[] a, int n)  
  19.  
  20. {  
  21.  
  22. if (a == null || n > a.Length || n < 1)   
  23. throw new ArgumentException();  
  24.  
  25. if (n == 1) return a[0];  
  26.  
  27. return Math.Max(FindMax(a, n - 1), a[n - 1]);  
  28.  
  29. }  
  30.  
  31. }  

第二种做法,不调用Math.Max方法。

  1. using System;  
  2.  
  3. class Program  
  4. {  
  5. static void Main()  
  6. {  
  7. int[] a = { 1, 210, 3, -51, 327, -58, 102300, 54343, -20, 0 };  
  8.  
  9. int max = FindMax(a, a.Length);  
  10.  
  11. Console.WriteLine("最大值: {0}", max);  
  12. }  
  13. static int FindMax(int[] a, int n)  
  14. {  
  15. if (a == null || n > a.Length || n < 1)   
  16. throw new ArgumentException();  
  17.  
  18. if (n == 1) return a[0];  
  19.  
  20. int max = FindMax(a, n - 1);  
  21.  
  22. if (a[n - 1] > max) max = a[n - 1];  
  23.  
  24. return max;  
  25. }  
  26. }  

关于C#递归函数的应用问题的介绍就到这里,希望对你了解和学习C#递归函数的应用有所帮助。

【编辑推荐】

  1. C#关机代码的实现浅析
  2. C#程序设计关闭Windows窗体浅析
  3. C#程序设计获取系统信息的Windows窗体浅析
  4. C#递归算法理解的实例分析
  5. C#递归思路的使用实例详解
责任编辑:仲衡 来源: 博客园
相关推荐

2009-09-02 19:12:37

C#递归

2009-09-03 15:43:21

C#时间计算

2009-09-04 18:09:12

C# Main函数

2009-09-01 15:47:20

C#取整函数

2009-09-01 17:08:14

C#画线控件

2009-09-09 14:40:15

C# XML解析

2009-09-02 18:44:19

C#递归

2009-09-01 17:41:53

C#截取字符串函数

2009-08-28 11:09:35

C#数组初始化

2009-09-07 06:31:32

C#窗体移动

2009-08-26 12:14:44

C#打印设置

2009-08-31 18:17:32

C#接口编程

2009-08-19 16:09:15

C#操作Access

2009-08-18 10:47:40

C#枚举类型

2009-09-09 13:57:28

C# XML解析

2009-09-03 10:52:41

C#递归树

2009-09-02 18:39:34

C#递归算法

2009-09-11 12:31:52

C#实例详解TypeConvert

2009-08-17 17:49:20

C# 枚举

2009-09-01 13:51:51

C#创建Word文档
点赞
收藏

51CTO技术栈公众号