2017-11-04 94 views
0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Changed from *int[,] matrix = new int[2, 2];* 
      int[,] matrix = new int[3, 3]; 
      // Still getting error with "[3,3]" 

      matrix[0, 0] = 1; 
      matrix[0, 1] = 2; 
      matrix[0, 2] = 3; 

      matrix[1, 0] = 4; 
      matrix[1, 1] = 5; 
      matrix[1, 2] = 6; 

      matrix[2, 0] = 7; 
      matrix[2, 1] = 8; 
      matrix[2, 2] = 9; 

      Console.Write(matrix[0, 2]); 

      Console.ReadKey(); 
     } 
    } 
} 

這是通過命令行執行的基本程序。多維數組:「索引超出了數組的範圍。」

在運行,而不是顯示存儲在數組中的數字「3」 [0,2],我帶有此錯誤:

System.IndexOutOfRangeException:「指數陣列的邊界之外「。

+0

它應該是'new int [3,3];',這裏的數字表示每個維度的長度。 –

+0

你可能想看看這個:https://stackoverflow.com/questions/3814145/how-can-i-declare-a-two-dimensional-string-array –

+0

我正在閱讀的書給我的印象是陣列從零開始向上計數,因此0,1,2將計爲「三」。 – Jojo

回答

0

「new int [2,2];」意味着矩陣是2 x 2. 您正在通過矩陣[0,2]訪問第3列,因此是例外。

0

@josias int[,] matrix = new int[2, 2];顯示您有一個2行2列的矩陣。但是在你的代碼中,你分配了3行3列的值。如果你有這樣的值,請使用下面的代碼。

int[,] matrix = new int[3, 3];

+0

我以爲我們從零開始計數? – Jojo

+0

我更新了原文。我已經改爲3 * 3矩陣,仍然出現「外界」的錯誤 – Jojo

0

這是直接從C# Specifications

Each dimension of an array has an associated length which is an integral number greater than or equal to zero. The dimension lengths are not part of the type of the array, but rather are established when an instance of the array type is created at run-time.

現在這是回答你的問題的一部分:

The length of a dimension determines the valid range of indices for that dimension: For a dimension of length N, indices can range from 0 to N - 1 inclusive.

因此,在您的案件的範圍將是0到2 - 1其中0和1.在一些語言如VB.NET中,你的假設是corr但不在C#中。

另請參閱this SO thread