C#入门学习——8

方法的功能一定要单一,最忌讳的就是出现提示用户输入的字眼。

方法的调用

我们在Main函数中调用某一个函数,我们管Main函数称之为调用者,x函数被称为被调用者。

如果被调用者想得到调用者的值,有两种方法

1是传参

int year = int.Parse(Console.ReadLine());
bool a = Years(year);//实参


public static bool Years(int year)//形参
{

}

不管是形参还是实参,都是在内存中开了空间的。

2是使用静态字段,模拟全局变量

public static int _number = 10;

如果调用者想要的到被调用者的值,返回值。

练习

//比较两个数字大小,返回最大的

public static int GetMax(int a,int b)
{
    int max = a > b ? a : b;
    return max;
}

static void Main(string[] args)
{
    Console.WriteLine("输入第一个数字");
    int number1 = int.Parse(Console.ReadLine());
    Console.WriteLine("输入第二个数字");
    int number2 = int.Parse(Console.ReadLine());
    int max = GetMax(number1,number2);
    Console.WriteLine(max);
    Console.ReadKey();
}

//读取输入的整数,多次调用,如果用户输入的是数字,则返回数字,否则重新输入

public static int GetNumber(string s)
{
    while(true)
    {
        try
        {
            int number = int.Parse(s);
            return number;
        }
        catch
        {
            Console.WriteLine("输入的不是数字,请重新输入");
            s = Console.ReadLine();
        }
    }
}
static void Main(string[] args)
{
    Console.WriteLine("输入一个数字");
    string input = Console.ReadLine();
    int number = GetNumber(input);
    Console.WriteLine(number);
    Console.ReadKey();
}

//只允许用户输入y/n,只要不是就重新输入

public static string GetInput(string s)
{
    while(true)
    {
        if(s=="y"||s=="n")
        {
            return s;
        }
        else
        {
            Console.WriteLine("只能输入y/n,请重新输入");
            s = Console.ReadLine();
        }
    }
}
static void Main(string[] args)
{
    Console.WriteLine("输入y/n");
    string s =GetInput(Console.ReadLine());
    Console.WriteLine(s);
    Console.ReadKey();
)

三个参数

out参数

out参数侧重于一个方法中返回多个不同类型的值,要求在方法内部必须为其赋值。

//分别的提示用户输入用户名和密码
//你写一个方法来判断用户输入的是否正确
//返回给用户一个登录结果,并且还要单独的返回给用户一个登录信息
//如果用户名错误,除了返回登录结果之外,还要返回一个用户名错误
//密码错误

public static bool LoginIn(string s1,string s2,out string msg)
{
    if(s1 == "admin" && s2 == "888888")
    {
        msg = "登录成功";
        return true;
    }
    else if(s2 == "888888")
    {
        msg = "用户名错误";
        return false;
    }
    else if(s1 == "admin")
    {
        msg = "密码错误";
        return false;
    }
    else
    {
        msg = "未知错误";
        return false;
    }
}     
static void Main(string[] args)
{
    Console.WriteLine("输入用户名");
    string s1 = Console.ReadLine();
    Console.WriteLine("输入密码");
    string s2 = Console.ReadLine();
    string msg;
    bool b = LoginIn(s1,s2,out msg);
    Console.WriteLine(b);
    Console.WriteLine(msg);
    Console.ReadKey();
} 

ref参数

ref参数能够将一个变量带入一个方法中改变,改变完之后再将改变完的值带出方法。

//使用方法来交换两个int类型的变量

public static void JiaoHuan(ref int n1,ref int n2)
{
    int temp = n1;
    n1 = n2;
    n2 = temp;
}

static void Main(string[] args)
{
    int n1 = 10;
    int n2 = 20;
    JiaoHuan(ref n1,ref n2)
    Console.WriteLine(n1);
    Console.WriteLine(n2);
    Console.ReadKey();
}

params可变参数

将实参列表中跟可变参数数组类型一致的元素当做数组的元素去处理。

params可变参数必须是参数列表的最后一个,且只能有一个。

static void Main(string[] args)
{
    int[] s = { 88, 8, 79 };
    Test("zhangsan", 99,88,77,100);
    Console.ReadKey();
}
public static void Test(string name,int id,params int[] score)
{
    int sum = 0;
    for (int i = 0; i < score.Length; i++)
    {
        sum += score[i];
    }
    Console.WriteLine("{0}这次考试的总成绩是{1}", name, sum);
}

这个时候的id是99,数组元素是{88,77,100}


TryParse方法

public static bool MyTryParse(string s,out int result)
{
    return 0;
    try
    {
        result = Convert.ToInt32(s);
        return true;
    }
    catch
    {
        return false;
    }
}


方法的重载和递归

重载

为什么有方法的重载?

方法的重载指的就是方法的名称相同,但是参数不同,方法的重载和返回值无关。

        public static void M(int n1,int n2)
        {
            int result = n1 + n2;
        }
        public static double M(double d1,double d2)
        {
            return d1 + d2;
        }
        public static void M(int n1,int n2,int n3)
        {
            int result = n1 + n2 + n3;
        }
        public static string M(string s1,string s2)
        {
            return s1 + s2;
        }
        

如上面四个方法,都是在做相加这件事,调用一个方法,传四种不同参数。

如果参数的个数相同,那么参数的类型就不能相同。

如果参数的类型相同,那么参数的个数就不能相同。

递归

比如我们想要找出一个文件夹中的所有文件,那么我们需要一个方法,能够找到一个指定文件夹下的所有文件。可能在这个文件夹下还有文件夹,这个时候就会使用到方法的递归。

public static int _i = 0;
public static void TellStory()
{
    //int i = 0;//如果在这里声明i,那么方法将进入死循环,需要使用静态字段
    Console.WriteLine("从前有座山");
    Console.WriteLine("山里有座庙");
    Console.WriteLine("庙里有个老和尚和小和尚");
    Console.WriteLine("老和尚给小和尚讲故事");
    _i++;
    if (_i >= 10)
    {
        return;
    }
    TellStory();         
}
static void Main(string[] args)
{
    TellStory();
    Console.ReadKey();
}

方法综合练习

1.//提示用户输入两个数字,计算这两个数字之间所有整数的和
   //用户只能输入数字
   //计算两个数字之间的和
   //要求第一个数字必须比第二个数字小,如果不,就重新输入

public static int GetNumber(string s)
{
    while(true)
    {
        try
        {
            int n = int.Parse(s)
            return n;
        }
        catch
        {
            Console.WriteLine("输入的不是数字,重新输入");
            s = Console.ReadLine();
        }
    }
}
public static void JudgeNumber(ref int n1,ref int n2)
{
    while(true)
    {
        if(n1>n2)//符合跳出
        {
            return;
        }
        else//n1>=n2
        {
            Console.WriteLine("输入的第二个数必须比第一个大,请输入第一个数"):
            string s1 = Console.ReadLine();
            n1 = GetNumber(s1);//用n1,n2接收
            Console.WriteLine("请输入第二个数");
            string s2 = Console.ReadLine();
            n2 = GetNumber(s2);
        }
    }
}
public static int GetSum(int n1,int n2)
{

    int sum = 0;
    for(i = n1; i < n2;i++)
    {
        sum+=n1;
    }
    return sum;
}
static void Main(string[] args)
{
    Console.WriteLine("请输入第一个数字");
    string strNumberOne = Console.ReadLine();
    //调用方法,将字符串转换成int类型,然后返回给我们,
    int numberOne = GetNumber(strNumberOne);
    Console.WriteLine("请输入第二个数字");
    string strNumberTwo = Console.ReadLine();
    int numberTwo = GetNumber(strNumberTwo);
    JudgeNumber(ref numberOne, ref numberTwo);//判断第一个数字是否小于第二个数字
                                              //把比较的结果带出,ref参数
    int sum = GetSum(numberOne, numberTwo);//求和
    Console.WriteLine(sum);
    Console.ReadKey();
}

2.//用方法来实现:有一个字符串数组
  //{"马龙","迈克尔乔丹","雷吉米欧","蒂姆邓肯","科比布莱恩特"},请输入出最长的

public static string GetMaxLength(string[] s)
{
    string max = s[0];//设定第一个为最长
    for(i = 0;i<s.Length;i++)
    {
        if(s[i].Length > max.Length)
        {
            max = s[i];
        }
    }
    return max;
}
static void Main(string[] args)
{
    string[] names = { "马龙", "迈克尔乔丹", "雷吉米欧", "蒂姆邓肯", "科比布莱恩特" };
    string maxLength = GetLongest(names);
    Console.WriteLine(maxLength);
    Console.ReadKey();
}

3.//用方法实现:请计算出一个整形数组的平均值。保留两位小数

public static double Avg(int[] s)
{
    double sum = 0;
    for(i = 0;i < s.Length;i++)
    {
        sum += s[i];
    }
    return Convert.ToDouble((sum/s.Length).ToString("0.00"));//真正保留两位
}
static void Main(string[] args)
{
    int[] nums = {1,2,7};
    double avg = Avg(nums);
    Console.WriteLine(avg);
    Console.ReadKey();
}

4.//写一个方法,用来判断用户输入的数字是不是质数
   //再写一个方法,要求用户只能输入数字,输入有误就重新输入

public static int GetNumber(string s)
{
    while(true)
    {
        try
        {
            int n = int.Parse(s);
            return n;
        }
        catch
        {
            Console.WriteLine("输入的不是数字,重新输入");
            s = Console.ReadLine();
        }
    }
}
public static bool ZhiShu(int n)
{
    if(n<2)//不是质数
    {
        return false;
    }
    else//>=2
    {
        for(i=2;i<n;i++)
        {
            if(n%i==0)//不是质数
            {
                return false;
            }
        }
        return true;
    }
}
static void Main(string[] args)
{
    Console.WriteLine("输入一个数字,判断是否为质数");
    string s = Console.ReadLine();
    int number = GetNumber(s);
    bool b = ZhiShu(number);
    Console.WriteLine(b);
    Console.ReadKey();
}

5.//接收输入后判断其等级并显示出来,判断依据如下:等级={优 (90-100);良 (80-89);中 (60-79); 差 (0-59)}

public static string Level(int n)
{
    if (n >= 90 && n <= 100)
    {
        return "优";
    }
    else if (n >= 80 && n < 90)
    {
        return "良";
    }
    else if (n >= 60 && n < 80)
    {
        return "中";
    }
    else
    {
        return "差";
    }
}
public static int GetNumber(string s)
{
    while(true)
    {
        try
        {
            int n = int.Parse(s);
            return n;
        }
        catch
        {
            Console.WriteLine("输入的不是数字,重新输入");
            s = Console.ReadLine();
        }
    }
}
static void Main(string[] args)
{
    Console.WriteLine("请输入一个成绩");
    string s = Console.ReadLine();
    int score = GetNumber(s);
    string level = Level(score);
    Console.WriteLine(level);
    Console.ReadKey();
}

6.//请将字符串数组{"中国","美国","加拿大","澳大利亚","巴西"}中的内容反转

public static void FanZhuan(string[] s)
{
    for(i=0;i<s.Length/2;i++)
    {
        string temp = s[i]
        s[i] = s[s.Length-1-i];
        s[s.Length-1-i] = temp;
    }
}
static void Main(string[] args)
{
    string[] country = { "中国", "美国", "加拿大", "澳大利亚", "巴西" };
    FanZhuan(country);
    for (int i = 0; i < country.Length; i++)
    {
        Console.WriteLine(country[i]);
    }
    Console.ReadKey();
}

7.//写一个方法 计算元的面积和周长 面积:pI*R*R 周长:2*Pi*r

public static void Yuan(double r,out double zhouChang,out double mianJi)
{
    mianJi = Math.PI * r * r;
    zhouChang = Math.PI * 2 * r;
}
static void Main(string[] args)
{
    double mianJi;
    double zhouChang;
    Console.WriteLine("输入圆的半径");
    double r = Convert.ToDouble(Console.ReadLine());
    Yuan(r, out zhouChang, out mianJi);
    Console.WriteLine(zhouChang);
    Console.WriteLine(mianJi);
    Console.ReadKey();
}

8.//计算任意多个数间的最大值(params)

public static int Max(params int[] n)
{
    int max = 0;
    for (int i = 0; i < n.Length; i++)
    {
        if (n[i] > max)
        {
            max = n[i];
        }
    }
    return max;
}
static void Main(string[] args)
{
    int max = Max(1, 2, 3, 4, 5, 6, 7);
    Console.WriteLine(max);
    Console.ReadKey();
}

9.//通过冒泡排序法对整个数组{1,3,5,7,90,2,4,6,8,10}实现升序排序

        public static void MaoPao(int[] s)
        {
            for (int i = 0; i < s.Length-1; i++)
            {
                for (int j = 0; j < s.Length-1; j++)
                {
                    if (s[j] > s[j + 1])
                    {
                        int n = s[j];
                        s[j] = s[j + 1];
                        s[j + 1] = n;
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            
            int[] nums = { 1, 3, 5, 7, 90, 2, 4, 6, 8, 10 };
            MaoPao(nums);
            for (int i = 0; i < nums.Length; i++)
            {
                Console.WriteLine(nums[i]);
            }
            Console.ReadKey();
        }

10.//将一个字符串数组,输出为|分割的形式,比如“梅西|卡卡|郑大世”

        static void Main(string[] args)
        {
            string[] names = { "梅西", "卡卡", "郑大世" };
            Test(names);
            Console.ReadKey();
        }
        public static void Test(string[] s)
        {
            for (int i = 0; i < s.Length-1; i++)
            {
                s[i] += "|";
            }
            for (int i = 0; i < s.Length; i++)
            {
                Console.Write(s[i]);
            }
        }

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值