使用Pascal创建一个正方形数组

时间:2016-04-26 16:44:03

标签: arrays matrix pascal

我需要创建一个程序,显示一个包含20行和20列的方阵(数组),然后给出该矩阵的最大值和最小值。

我从这段代码开始:

program ex2dimarray;
var
    a: array [0..20, 0..20] of integer;
    i, j: integer;

begin
    for i := 0 to 3 do
        for j := 0 to 3 do
            a[i,j] := i * j;

    for i := 0 to 3 do
    begin
        for j := 0 to 3 do
            write(a[i,j]:2, ' ');
        writeln;
    end;
end.

2 个答案:

答案 0 :(得分:0)

program ex2dimarray;

var
 a: array [0..20, 0..20] of integer;
 m, i, j: integer;

begin

//filling the array, in any way you like

for i := 0 to 19 do
    for j := 0 to 19 do
        a[i,j] := i * j;


//scanning for max value

m :=0;
for i := 0 to 19 do
    for j := 0 to 19 do
       if m<=a[i,j] then m:=a[i,j] ;

//print the array

for i := 0 to 19 do
begin
    for j := 0 to 19 do
        write(a[i,j]:2, ' ');
    writeln;
end;

//print the max value

writeln('Maximum is ',m);

end.

答案 1 :(得分:-1)

您声明了一个20x20的数组,但在您的代码中,您只使用了3x3块。此外,缺少查找最大值和最小值的逻辑。

您可以尝试这样的事情:

program ex2dimarray;
const 
    Dim = 20;

var
    a: array [0..Dim, 0..Dim] of integer;
    i, j, min, max: integer;

begin
    // initialize the array
    for i := 0 to Dim do
    begin
        for j := 0 to Dim do
            a[i,j] := i * j;
    end;

    // search for max and min. You can initialize both to a[0,0]
    min:= maxint;
    max:= -maxint;

    for i := 0 to Dim do
    begin
        for j := 0 to Dim do
        begin
            if (a[i,j] > max) then
                max := a[i,j];

            if (a[i,j] < min) then
                min := a[i,j];
        end;
    end;

    // print out the values
    for i := 0 to Dim do
    begin
        for j := 0 to Dim do
            write(a[i,j]:3, ' ');
        writeln;
    end;
    writeln;
    write('Max: ', max, '     Min: ', min);
    writeln;
    readln;
end.