2016-12-05 71 views
1

問題描述阿達:索引在for循環一個數組範圍具有意外的值

我想每一個元素遍歷以矩陣和顯示:

  • 元素值
  • 元素索引(I,J)

下面的代碼給我下面的輸出:

(-2147483648, -2147483648) = 1.00000E+00 
(-2147483648, -2147483647) = 2.00000E+00 
(-2147483648, -2147483646) = 3.00000E+00 
(-2147483647, -2147483648) = 4.00000E+00 
(-2147483647, -2147483647) = 5.00000E+00 
(-2147483647, -2147483646) = 6.00000E+00 

我期望看到1而不是-2147483648和2而不是-2147483647。

樣品編號

with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays; 
with Ada.Text_IO;    use Ada.Text_IO; 

procedure Index is 
    Matrix : Real_Matrix := ((1.0, 2.0, 3.0), 
          (4.0, 5.0, 6.0)); 
begin 
    for I in Matrix'Range(1) loop 
     for J in Matrix'Range(2) loop 
     Put_Line("(" & Integer'Image(I) & ", " & 
        Integer'Image(J) & ") = " & 
        Float'Image(Matrix(I, J))); 
     end loop; 
    end loop; 
end Index; 
+3

顯然,Real_Matrix類型使用'Integer'作爲其索引類型 - 如果沒有特別指明,默認值是'整」 First'。在Ada中,我們鼓勵您聲明和使用適合您問題的自己的類型,因此應使用Natural(從0開始)或Positive(您得到它)或ranged子類型聲明一個數組類型(沿着Real_Matrix的線),並使用那。 –

回答

5

Real_Matrix的索引類型是Integer,這在-2147483648開始你的平臺,這也解釋了你所看到的數字上。然而,由於該類型是不受約束的,你可以在一個陣列合計指定自己的指數:

Matrix : Real_Matrix := (1 => (1 => 1.0, 2 => 2.0, 3 => 3.0), 
          2 => (1 => 4.0, 2 => 5.0, 3 => 6.0)); 
+0

感謝egilhh和Brian的快速反應! – evilspacepirate