[英]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.