我有一个输出3(4x4)矩阵(不同数量,相同布局)的程序
我必须再次输出矩阵,其中元素数和是最大的。
例如65是最大元素数和。
1 2 3 4 10 1 2 3 4 10 1 1 1 1 4
5 6 7 8 26 2 3 4 5 14 2 2 2 2 8
9 1 2 3 15 3 4 5 6 18 3 3 3 3 12
2 3 4 5 14 4 5 6 7 22 4 4 4 4 16
65 64 40
生成3个随机矩阵的程序:
uses
SysUtils;
var
i: integer;
x: integer;
y: integer;
matrix: array[1..4, 1..4] of integer;
begin
randomize;
for i := 1 to 3 do
begin
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;
writeln;
end;
readln;
end.
你能帮帮我吗?我会非常感激。
答案 0 :(得分:1)
例如可以这样:
program Project1;
uses
SysUtils;
// create a type for the matrix
type
TMatrix = array[1..4, 1..4] of Integer;
var
I: Integer;
X: Integer;
Y: Integer;
CurSum: Integer;
MaxIdx: Integer;
MaxSum: Integer;
Matrices: array[1..3] of TMatrix;
begin
// initialize random seed
Randomize;
// initialize max. sum matrix index and max. matrix sum
MaxIdx := 0;
MaxSum := 0;
// iterate to create 3 matrices
for I := 1 to 3 do
begin
// initialize sum value of this matrix to 0
CurSum := 0;
// iterate to fill the matrices with random values
for X := 1 to 4 do
for Y := 1 to 4 do
begin
// to the matrix I assign a random value to the X, Y position
Matrices[I][X, Y] := Random(101);
// add this random value to the current matrix sum value
CurSum := CurSum + Matrices[I][X, Y];
end;
// check if this matrix sum value is greater than the stored one
// and if so, then...
if CurSum > MaxSum then
begin
// store this matrix index
MaxIdx := I;
// and store this matrix sum as a max sum value
MaxSum := CurSum;
end;
// print out this matrix
for X := 1 to 4 do
begin
for Y := 1 to 4 do
Write(IntToStr(Matrices[I][X, Y]), ' ');
WriteLn;
end;
WriteLn;
end;
// print out the index of the matrix with max sum and its sum value
WriteLn;
WriteLn('The biggest matrix is the ' + IntToStr(MaxIdx) + '. one. The sum ' +
'of this matrix is ' + IntToStr(MaxSum) + '.');
WriteLn;
// and print out that matrix with max sum value
for X := 1 to 4 do
begin
for Y := 1 to 4 do
Write(IntToStr(Matrices[MaxIdx][X, Y]), ' ');
WriteLn;
end;
ReadLn;
end.