首页 > 代码库 > 14、函数输出参数、递归

14、函数输出参数、递归

1、函数输入参数对于函数而言,相当于已经赋值了的变量,直接可用。输出参数相当于定义了一个变量,需要在函数中为其赋值,然后调用函数的时候将所赋值带出函数。例1:输入a,b,c的值,判断是不是一个一元二次方程:class Program    {        public string fangcheng(double a, double b, double c, out double x1, out double x2)        {            double d = b * b - 4 * a * c;            if (a == 0)            {                          x1 = -b/c;                x2 = -b/c;                return "不是一元二次方程";            }            else             {                     if (d < 0)                {                                    x1 = -1;                    x2 = -1;                    return "无解";                }                else if (d == 0)                {                                       x1 = -(b + Math.Sqrt(d)) / (2 * a);                    x2 = -(b - Math.Sqrt(d)) / (2 * a);                    return "有两个相等的实数根";                }                else                 {                                      x1 = -(b + d) / (2 * a);                    x2 = -(b - d) / (2 * a);                    return "有两个不相等的实数根";                }            }        }        static void Main(string[] args)        {            Program aaa = new Program();            Console.WriteLine("请输入a的值:");            double a = int.Parse(Console.ReadLine());            Console.WriteLine("请输入b的值:");            double b = int.Parse(Console.ReadLine());            Console.WriteLine("请输入c的值:");            double c = int.Parse(Console.ReadLine());            double x1, x2;            Console.WriteLine(aaa.fangcheng(a,b,c,out x1,out x2));            Console.WriteLine("x1=" + x1 +"\n"+ "x2=" + x2);            Console.ReadLine();        }}2、递归例2:(1)猴子摘桃子,后一天摘前一天的一半加一个,第七天还有一个,总共有几个?(2)一人赶着一群羊,到一个村就卖掉1/3加一只,到第七个村庄时还有2只,总共有几只?(3)一对幼兔两个月长成成兔并生下一对幼兔,9个月后有几对?class Program    {        public int taozi(int day)        {            if (day == 7)            {                return 1;            }            else            {                int n = 2 * (taozi(day + 1) + 1);                return n;            }        }        public int yang(int cun)        {            if (cun == 7)            {                return 2;            }            else            {                int n = 3 * (yang(cun + 1) + 1);                return n;            }        }        public int tuzi(int yue)        {            if (yue == 0)            {                return 1;            }            else            {                int n = tuzi(yue-2)*2;                return n;            }        }        static void Main(string[] args)        {            Program dd = new Program();            Console.WriteLine(dd.taozi(1));            Console.WriteLine(dd.yang(1));            Console.WriteLine(dd.tuzi(9));            Console.ReadLine();        }}

 

14、函数输出参数、递归