函数/方法:
非常抽象
独立完成某项功能的一个个体
提高代码的重用性
提高功能开发的效率
提高程序代码的可维护性
固定功能函数
高度抽象函数
函数四要素:
输入,输出,函数体,函数名
public static 返回值类型 函数名(需要的参数,第二个,int a,string b)
{
return 上面的返回值类型;
}
public static string shoushi(int a, int b) { // 0-拳头,1-剪子,2包袱 int e = a - b; string d = ""; if (e == -1 || e == 2) { d = "1号选手获胜!"; return d; } if (e == -2 || e == 1) { d = "2号选手获胜!"; return d; } if (e == 0) { d = "平局!"; return d; } else { d = "手势有误"; return d; } } public static string zh(int a) { string b = ""; if (a == 0) { b = "拳头"; return b; } if (a == 1) { b = "剪子"; return b; } if (a == 2) { b = "包袱"; return b; } else { b = "数字错误!"; return b; } } static void Main(string[] args) { Console.Write("请输入1号选手手势(0-拳头,1-剪子,2-包袱):"); int no1 = Convert.ToInt32(Console.ReadLine()); Console.Write("请输入1号选手手势(0-拳头,1-剪子,2-包袱):"); int no2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("选手1的手势为"+Program.zh(no1)+" 选手2的手势为"+Program.zh(no2)+" "+Program.shoushi(no1,no2)); //防闪退 Console.ReadLine();
函数的多种形态:
1、有参数,有返回值
2、无参数,无返回值
适用极少,不推荐
namespace ConsoleApplication1 { class Program { public static void leixing1() { Console.Write("输出内容"); } static void Main(string[] args) { Program.leixing1 (); } //局限性大 } }
3、有参数,无返回值
namespace ConsoleApplication1 { class Program { public static void leixing2(int a,int b) { Console.Write("输出内容"+(a+b)); } static void Main(string[] args) { Program.leixing2 (10,20); } //需要参数,给你一个具体结果,不好使 } }
4、无参数,有返回值
namespace ConsoleApplication1 { class Program { public static int leixing3() { return 20; } static void Main(string[] args) { Program.leixing3 (); } //可以用变量进行定义 } }
函数返回多个值的办法:
ref - 可出可进 在方法内可重新赋值
namespace ConsoleApplication1 { class Program { public static int leixing4( ref int a, int b) { a = 10; return a + b; } static void Main(string[] args) { int c = 12; int d = 13; int e = Program.leixing4( ref c,d); } } }
out - 只出不进 无论在外面你有没有赋值,只调用方法内的值
namespace ConsoleApplication1 { class Program { public static int leixing4( out int a, int b) { a = 10; return a + b; } static void Main(string[] args) { int c = 12; int d = 13; int e = Program.leixing4( out c,d); } } }
递归:
递进去,归还回来的一个过程
使用的方法:
函数调用它本身
public static void fb(int a) { if ( a>5) { return; } a++; fb(a);//到此位置时,为进入过程,进入但全过程并未完结,直接进入下一层过程 a--; return;//此处跳出只跳出当前过程,并非全部 }