繁体   English   中英

在主C#中获取方法

[英]Getting a Method in the Main C#

     static void bubble(int [] mas)
    {
        int temp;
        for (int i = 0; i < mas.Length; i++)
        {
            for (int j = 0; j < mas.Length - 1; j++)
                if (mas[j] > mas[j + 1])
                {
                    temp = mas[j + 1];
                    mas[j + 1] = mas[j];
                    mas[j] = temp;
                }

        }
        foreach (var element in mas)
        {
            Console.WriteLine("Sorted elements are: {0}", element);

        }

    }

    static void Main(string[] args)
    {
        int[] mas = new int[5];
        Console.WriteLine("Please enter the elements of the array: ");
        for (int i = 0; i < 5; i++)
        {
            mas[i] = Convert.ToInt32(Console.ReadLine());
        }
        bubble();
    }

我需要使用方法来解决Uni项目的某些任务,而我遇到的问题是我想在Main中创建一个数组,在其他方法中使用它,然后将这些方法的结果返回Main。 当我这样做并尝试将“气泡”重新调用到Main时,它告诉我没有给定的参数与形式上给定的参数相对应。 有没有简单的方法可以解决此问题,因此我可以修复该问题并继续以类似方式创建其他方法。 提前致谢

出现错误的原因是因为函数bubble需要int[]作为参数。

当前,您有bubble() ,其当前状态为“无参数”

bubble(mas);代替bubble(mas);

您需要在main的Bubble调用中传递参数:

bubble(mas);

像这样更改您的代码:

static int[] bubble(int [] mas)
    {
        int temp;
        for (int i = 0; i < mas.Length; i++)
        {
            for (int j = 0; j < mas.Length - 1; j++)
                if (mas[j] > mas[j + 1])
                {
                    temp = mas[j + 1];
                    mas[j + 1] = mas[j];
                    mas[j] = temp;
                }

        }
        foreach (var element in mas)
        {
            Console.WriteLine("Sorted elements are: {0}", element);

        }

    }

    static void Main(string[] args)
    {
        int[] mas = new int[5];
        Console.WriteLine("Please enter the elements of the array: ");
        for (int i = 0; i < 5; i++)
        {
            mas[i] = Convert.ToInt32(Console.ReadLine());
        }
        bubble(mas);
    }

暂无
暂无

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

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