数组索引中的Ada类型冲突

时间:2016-10-16 19:09:11

标签: arrays types ada

这是代码,算法在Java中工作,但在Ada中,它仍然会引发CONSTRAINT_ERROR。在Ada中,我们开始将数组索引为1而不是0,就像大多数其他语言一样。出于某种原因,我仍在索引数组。

 procedure spiral is

   M : Matrix := ((11,22,33,44,55),(1,8,3,8,9),(10,10,20,30,1));

   lastcol, firstcol, lastrow : Integer := 1;
   rowsize, colsize : Integer := 0;

   procedure Print ( M: in Matrix ) is
   begin

  rowsize := M'Length(1);
  colsize := M'Length(2);

  while lastrow<=rowsize loop

        for I in Index range Index(firstcol)..Index(colsize) loop
           Put( Elem'Image(M(Index(lastrow),Index(I))));
           Put( Ascii.HT );
        end loop;

        lastrow := lastrow + 1;

        if (lastrow>=rowsize) then 
           return;
        end if;

        for J in Index range Index(lastrow)..Index(rowsize) loop
           Put( Elem'Image(M(Index(J),Index(colsize))));
           Put( Ascii.HT );
        end loop;

        colsize := colsize - 1;


        for I in reverse Index range Index(colsize)..Index(lastcol) loop
           Put( Elem'Image(M(Index(rowsize), Index(I))));
           Put( Ascii.HT );
        end loop;

        rowsize := rowsize- 1;
        lastcol := lastcol+ 1;

        for I in reverse Index range Index(rowsize)..Index(lastrow) loop
           Put( Elem'Image(M(Index(I), Index(firstcol))));
           Put( Ascii.HT );
        end loop;

        firstcol := firstcol + 1;

     end loop;
   end Print;

begin
   --Put(rowDown);
   Print(M);
end spiral;

Matrix包定义为:

package Matrix_pack is

    type Index is new Integer;
    type Elem is new Integer;
    type Matrix is array (Index range <>, Index range <>) of Elem;

end Matrix_pack;

1 个答案:

答案 0 :(得分:2)

解决方案可以分两步完成:

  • 首先:使循环中使用的索引类型显式:
for I in Index range colLeft .. colRight loop
   Put (Elem'Image (M (rowUp, I)));
end loop;
  • 第二:修复colLeftcolRight
  • 的声明
colLeft, colRight : Index;