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

第一种做法,调用Math.Max的方法来比较大小。
- using System;
 - class Program
 - {
 - static void Main()
 - {
 - int[] a = { 1, 210, 3, -51, 327, -58, 102300, 54343, -20, 0 };
 - int max = FindMax(a, a.Length);
 - Console.WriteLine("最大值: {0}", max);
 - }
 - static int FindMax(int[] a, int n)
 - {
 - if (a == null || n > a.Length || n < 1)
 - throw new ArgumentException();
 - if (n == 1) return a[0];
 - return Math.Max(FindMax(a, n - 1), a[n - 1]);
 - }
 - }
 
第二种做法,不调用Math.Max方法。
- using System;
 - class Program
 - {
 - static void Main()
 - {
 - int[] a = { 1, 210, 3, -51, 327, -58, 102300, 54343, -20, 0 };
 - int max = FindMax(a, a.Length);
 - Console.WriteLine("最大值: {0}", max);
 - }
 - static int FindMax(int[] a, int n)
 - {
 - if (a == null || n > a.Length || n < 1)
 - throw new ArgumentException();
 - if (n == 1) return a[0];
 - int max = FindMax(a, n - 1);
 - if (a[n - 1] > max) max = a[n - 1];
 - return max;
 - }
 - }
 
关于C#递归函数的应用问题的介绍就到这里,希望对你了解和学习C#递归函数的应用有所帮助。
【编辑推荐】
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号