2016-12-05 67 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