Latest web development tutorials

C# 傳遞數組給函數

C# 數組 C#數組

在C# 中,您可以傳遞數組作為函數的參數。 您可以通過指定不帶索引的數組名稱來給函數傳遞一個指向數組的指針。

實例

下面的實例演示瞭如何傳遞數組給函數:

using System;

namespace ArrayApplication
{
   class MyArray
   {
      double getAverage(int[] arr, int size)
      {
         int i;
         double avg;
         int sum = 0;

         for (i = 0; i < size; ++i)
         {
            sum += arr[i];
         }

         avg = (double)sum / size;
         return avg;
      }
      static void Main(string[] args)
      {
         MyArray app = new MyArray();
         /* 一個帶有5 個元素的int 數組*/
         int [] balance = new int[]{1000, 2, 3, 17, 50};
         double avg;

         /* 傳遞數組的指針作為參數*/
         avg = app.getAverage(balance, 5 ) ;

         /* 輸出返回值*/
         Console.WriteLine( "平均值是: {0} ", avg );
         Console.ReadKey();
      }
   }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

平均值是: 214.4

C# 數組 C#數組