我必须在FreePascal中随机制作二维数组(4x4)。每个元素必须在0到100之间。
例如:12 99 1 85
43 75 5 11
0 100 77 31
64 15 9 74
我试过了,但是不工作:
var
row:array[1..4] of string = (random(100));
column:array[1..4] of string = (random(100));
matrix:array[1..4,1..4] of string;
x:integer;
y:integer;
begin
for x := 1 to 4 do
for y := 1 to 4 do
matrix[x,y] := row[x] + column[y];
for x := 1 to 4 do
for y := 1 to 4 do
write(matrix[x,y], ' ');
end.
给出错误:
Illegal expression
Expected another 3 array elements
Illegal expression
Expected another 3 array elements
你能帮我吗?
您的row
和column
变量是错误的,因为您不能通过函数调用初始化数组。这些变量甚至是不必要的,因为你已经定义了matrix
。我已经将matrix
变量类型更改为整数的多维数组。该代码生成0-100范围内的随机数;0和100,包括。
program Project1;
uses
SysUtils;
var
X: Integer;
Y: Integer;
Matrix: array[1..4, 1..4] of Integer;
begin
Randomize;
for X := 1 to 4 do
for Y := 1 to 4 do
Matrix[X, Y] := Random(101);
for X := 1 to 4 do
begin
for Y := 1 to 4 do
Write(IntToStr(Matrix[X, Y]), ' ');
WriteLn;
end;
ReadLn;
end.
您已将行、列和矩阵声明为字符串数组。
将其改为整数数组
你需要在运行时定义你的行和列数组。
var
row : array[1..4] of Integer;
column : array[1..4] of Integer;
matrix : array[1..4,1..4] of Integer;
x:integer;
y:integer;
begin
Randomize; // Init random generator
for x := 1 to 4 do
begin
row[x] := Random(51);
column[x] := Random(51);
end;
for x := 1 to 4 do
for y := 1 to 4 do
matrix[x,y] := row[x] + column[y];
for x := 1 to 4 do
begin
for y := 1 to 4 do
begin
write(IntToStr(matrix[x,y]), ' ');
end;
WriteLn;
end;
ReadLn;
end.