C#8方法

方法的声明及调用

c#的方法类似于c的函数
在这里插入图片描述

计算8,7,6,5的阶乘

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _8._1方法的声明及使用
{
   
    class Program
    {
   
        //void表示没有返回值,有返回值的话,直接用对应的类型替换
        static void Factorial(int num)//创建方法
        {
   
            int factorial = 1;
            for (int i = num; i > 0; i--)
            {
   
                factorial *= i;
            }
            Console.WriteLine("{0}的阶乘是:{1}", num, factorial);
        }

        static int Add(int a,int b)
        {
   
            return a + b;
        }
       
        static void Main(string[] args)
        {
   
            Factorial(8);//调用方法
            Factorial(7);
            Factorial(6);
            Factorial(5);

            int c = Add(25, 30);
            Console.WriteLine(c);

            Console.ReadKey();
        }
    }
}


结果:

8的阶乘是:40320
7的阶乘是:5040
6的阶乘是:720
5的阶乘是:120
55

在这里插入图片描述在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _8._2方法的声明与调用_2_
{
   
    class Program
    {
   
        //编写一个方法用于计算给定整型数组元素的和
        static int Add(params int[] nums)
        {
   
            int sum = 0;
            foreach(int outnum in nums)
            {
   
                sum += outnum;
            }
            return sum;
        }
        static void Main(string[] args)
        {
   
            int[] myintArray = {
    2, 45, 67, 54, 788, 435, 345 };
            Console.WriteLine(Add(myintArray));
            Console.ReadKey();
        }
    }
}

结果:

1736

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _8._2方法的声明与调用_2_
{
   
    class Program
    {
   
        //编写一个方法用于求平方(没有返回值)
        //此时的参数传递就叫做值传递
        static void Square(int num)
        {
   
            num *= num;
            Console.WriteLine("num的平方是" + num);
        }

        static void Main(string[] args)
        {
   
            int num = 10;
            Console.WriteLine(num);
            Square(num);
            Console.WriteLine(num);
            Console.ReadKey();
        }
    }
}

结果:

10
num的平方是100
10

using System;
using System.Collections.Generic;
using System
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值