Ada:数组范围内 for 循环中的索引具有意外值
Ada: Index in for loop over an array range has unexpected value
问题陈述
我想遍历矩阵中的每个元素并显示:
- 元素值
- 元素索引 (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;
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 ));
问题陈述
我想遍历矩阵中的每个元素并显示:
- 元素值
- 元素索引 (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;
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 ));