一 函数
独立完成某项功能的一个个体,有固定功能函数有 高度抽象函数。
1、作用:
提高代码的重用性
提高功能开发的效率
提高程序代码的可维护性
2、函数四要素:
输入 输出 函数名 函数体
函数名与函数体必不可少
3、表达式 (Main函数外)
public static 返回值类型 函数名( 函数参数 ) { ......... return 返回值类型 ; }
public static int Jia10 ( int a ) //函数名最好取动词 { //函数参数仅告诉需要输入的参数类型 int b = a + 10 ; return b; }
4 返回两个值的情况
(1) ref 调用外部变量,函数中对对变量的任何改变都会映射到变量本身。
public static int test ( ref int a , int b ) { a = 5; retrun a + b ; } static void Main ( string [ ] arg s ) { int i = 2 ; int j = 10; int c = program.test (ref i , j ) Console.WriteLine( i ); Console.WriteLine( c ); } //输出结果 i = 5; c = 15
(2) out 在函数方法中只出不进,不将值带入方法内部,但能够将内部的值带出。
public static int test ( out int a , int b ) { a = 5; retrun a + b ; } static void Main ( string [ ] arg s ) { int i = 0 ; int j = 10; int c = program.test (ref i , j ) Console.WriteLine( i ); Console.WriteLine( c ); } //输出结果 i = 5 ; c = 15
5、 函数的多种形态
(1) 有参数有返回值,(表达式例句)
(2)无参数无返回值
public static void test () { Console.WriteLine( " 哈哈哈哈" ); //不论参数如何 只要调用只会输出“哈哈哈哈” }
(3)有参数无返回
public static void test2 ( int a; int b } { Console.WriteLine( a+b ); // void 声明无返回值 }
(4)无参数有返回值
public static int test3 ( ) { return 20 ; //retrun 声明返回 }
二 递归
函数体内调用本函数自身,直到符合某一条件不再继续调用。
1、满足条件
调用自身
有跳出反复执行过程的条件
2、注意事项
递归中必须存在一个循环结束的条件。
递归函数的每次调用都需要栈在存储,如果次数太多的话容易造成栈溢出。
3、实例
public static void test ( int a ) { if(a<3) retrun; Console.WriteLine( "这是第“+a+”层梦境" ); //递归中 retrun 声明跳出 a++ test(a); a-- Console.WriteLine("第"+a+"层梦境醒了"); }