繁体   English   中英

C#(找到第二大数字)如何在子程序中拆分程序?以便以后可以重用代码……?

[英]C# (find second largest number) How to split program in subprograms ?so I can reuse code later…?

我有这个程序,它从用户输入中查找第二大数字,用户需要输入至少2个数字和最大10个数字。我想将程序分为子程序(至少主程序和一个函数)。 我不能让它工作:(

单位 码:

 static void Main(string[] args)
    {
        int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0;

        while (n != 0 && i < 10)
        {
            Console.WriteLine("Input number");
            n = int.Parse(Console.ReadLine());
            //I want this part to be in a function from here.
            if (n > max)
            {
                smax = max;
                max = n;
            }
            else if (n > smax)
            {
                smax = n;
            }
            //to here
            if (n == smax)
            {
                ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1  it outputs error
            }

            i++;
        }
        if (smax != 0 && smax != ISsmaxrepeating)
        {

            Console.WriteLine("secondmax is {0}", smax);

        }
        else
        {
            Console.WriteLine("error");
        }
        Console.ReadLine();

到目前为止,我想出了这个,但它没有用:(

 static int checking(int n, int max, int smax)
    {
        if (n > max)
        {
            smax = max;
            max = n;
        }
        else if (n > smax)
        {
            smax = n;
        }
        return n;
    }
    static void Main(string[] args)
    {
        int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0, result = 0;

        while (n != 0 && i < 10)
        {
            Console.WriteLine("Input number");
            n = int.Parse(Console.ReadLine());

            result = checking(n,max,smax);

            if (n == smax)
            {
                ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1  it outputs error
            }

            i++;
        }
        if (smax != 0 && smax != ISsmaxrepeating)
        {

            Console.WriteLine("secondmax is {0}", smax);

        }
        else
        {
            Console.WriteLine("error");
        }
        Console.ReadLine();


    }

您可以使用ref关键字从函数输出多个变量。 但是,最好不要对此类操作使用函数。

static void checking(int n, ref int max, ref int smax)
{
    if (n > max)
    {
        smax = max;
        max = n;
    }
    else if (n > smax)
    {
        smax = n;
    }
}

调用Main内部的函数

checking(n, ref max, ref smax);

为什么不使用Math.max或Math.min? 如果要查找3个数字之间的最大值,请先执行int halfmax = math.max(firstnum,secondnum),然后再执行int max = Math.max(halfmaz,thirdnum)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM