十四、函数
(一)定义
1、定义与格式
函数即方法
class Program { //格式一:没有返回值,没有参数 public void qiuhe() { Console.Write("请输入一个数:"); int a = int.Parse(Console.ReadLine()); int sum = 0; for (int i = 1; i <= a; i++) { sum += i; } Console.WriteLine(sum); } //格式二:没有返回值,有参数 public void qiuhe(int a) { int sum = 0; for (int i = 1; i <= a; i++) { sum += i; } Console.WriteLine(sum); } //格式三:有返回值,但无参数 public int qiuhe0() { Console.Write("请输入一个数:"); int a = int.Parse(Console.ReadLine()); int sum = 0; for (int i = 1; i <= a; i++) { sum += i; } return sum; } //格式四:有返回值,且有参数 public int qiuhe1(int a) { int sum = 0; for (int i = 1; i <= a; i++) { sum += i; } return sum; } static void Main(string[] args) { Program function = new Program(); //初始化这个类,是为了调用这个类里面的函数 function.qiuhe(); //函数只有调用才会执行。无返回值,无参数 (调用格式一) Console.Write("请输入一个数:"); int a = int.Parse(Console.ReadLine()); function.qiuhe(a); //无返回值,有参数 (调用格式二) int sum0 = function.qiuhe0(); //无返回值,无参数 (调用格式三) Console.WriteLine(sum0); int sum1 = function.qiuhe1(a); //有返回值,有参数 (调用格式四) Console.WriteLine(sum1); Console.ReadLine(); }
(二)例题
1、求最大值
主要代码:
class Program { /// <summary> /// 两个值进行比较,返回较大值,若相等返回任意一个。 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public double max(double a, double b) { if (a > b) return a; else return b; } static void Main(string[] args) { Program function = new Program(); double a = 4, b = 5, c = 3; Console.WriteLine(function.max(function.max(a, b), c)); Console.ReadLine(); }
结果:
2、求阶乘的累加和
主要代码:
static void Main(string[] args) { Program method = new Program(); method.sum();//格式一 Console.WriteLine(); Console.Write("请输入:");//格式二 int num = int.Parse(Console.ReadLine()); method.sum(num); Console.WriteLine(); int sum = method.Sum();//格式三 Console.WriteLine(sum); Console.WriteLine(); Console.Write("请输入:");//格式四 int Num = int.Parse(Console.ReadLine()); int Sum = method.Sum(Num); Console.WriteLine(Sum); Console.ReadLine(); } public void sum()//格式一 { Console.Write("请输入:"); int num = int.Parse(Console.ReadLine()); int sum = 0; for (int i = 1; i <= num; i++) { int factorial = 1; for (int j = 1; j <= i; j++) { factorial *= j; } sum += factorial; } Console.WriteLine(sum); } public void sum(int num)//格式二 { int sum = 0; for (int i = 1; i <= num; i++) { int factorial = 1; for (int j = 1; j <= i; j++) { factorial *= j; } sum += factorial; } Console.WriteLine(sum); } public int Sum()//格式三 { Console.Write("请输入:"); int num = int.Parse(Console.ReadLine()); int sum = 0; for (int i = 1; i <= num; i++) { int factorial = 1; for (int j = 1; j <= i; j++) { factorial *= j; } sum += factorial; } return sum; } public int Sum(int num)//格式四 { int sum = 0; for (int i = 1; i <= num; i++) { int factorial = 1; for (int j = 1; j <= i; j++) { factorial *= j; } sum += factorial; } return sum; }
结果:
时间: 2024-10-05 20:54:21