2017-02-15 24 views
0

有人可以解釋爲什麼我得到這個界限? 下面是代碼:獲得索引是在數組的外界

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace testing 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var n = int.Parse(Console.ReadLine()); 
      double[] numbers = new double[] { }; 
      for(int i = 0; i < n; i++) 
      { 
       var input = double.Parse(Console.ReadLine()); 
       numbers[i] = input; 
      } 
      Console.WriteLine(numbers); 
     } 
    } 
} 

回答

0

您沒有設置數組大小

double[] numbers = new double[n] 
0

的陣列在初始化時固定長度。您的尺寸爲0.

double[] numbers = new double[] { }; // { } is the same as 'initialize with 0 elements or no content' 

您需要使用List而不是Array。

List<double> numbers = new List<double>(); 

for(int i = 0; i < n; i++) 
{ 
    var input = double.Parse(Console.ReadLine()); 
    numbers.Add(input); 
} 
+0

謝謝你的幫助 –