Magic Square FreePascal

时间:2013-04-07 22:00:55

标签: pascal freepascal magic-square

程序必须输出方形是否为幻方。

我必须从文件中读取方块。

幻方 - 所有行,所有列和两个对角线总和必须相等。

程序显示正确答案,但必须从文本文件中读取这16个数字。

文本文件看起来像:

1 1 1 1
2 2 2 2 
3 3 3 3
4 4 4 4

编程本身:

var
  m:array[1..4,1..4] of integer;
  i:byte;
  j:byte;
  r1,r2,r3,r4,c1,c2,c3,c4,d1,d2:integer;

begin

for i:=1 to 4 do
  for j:=1 to 4 do

  begin
    write('Enter value for column=',i,' row=',j,'  :');
    readln(m[i,j]);
  end;

r1:=m[1,1]+m[1,2]+m[1,3]+m[1,4];
r2:=m[2,1]+m[2,2]+m[2,3]+m[2,4];
r3:=m[3,1]+m[3,2]+m[3,3]+m[3,4];
r4:=m[4,1]+m[4,2]+m[4,3]+m[4,4];
c1:=m[1,1]+m[2,1]+m[3,1]+m[4,1];
c2:=m[1,2]+m[2,2]+m[3,2]+m[4,2];
c3:=m[1,3]+m[2,3]+m[3,3]+m[4,3];
c4:=m[1,4]+m[2,4]+m[3,4]+m[4,4];
d1:=m[1,1]+m[2,2]+m[3,3]+m[4,4];
d2:=m[1,4]+m[2,3]+m[3,2]+m[4,1];

if (r1=r2) and (r2=r3) and (r3=r4) and (r4=c1) and (c1=c2) and (c2=c3) and (c3=c4) and (c4=d1) and (d1=d2) then
  begin
  write('Magic Square');
  end

else
  begin
  write('Not Magic Square');
  end;

readln;

end.

1 个答案:

答案 0 :(得分:1)

以下是从文本文件中读取矩阵的过程。 行元素应该用空格分隔。

type
  TMatrix = array[1..4,1..4] of integer;

procedure ReadMatrix( const filename: String; var M: TMatrix);
var
  i,j : integer;
  aFile,aLine : TStringList;
begin
  aFile := TStringList.Create;
  aLine := TStringList.Create;
  aLine.Delimiter := ' ';
  try
    aFile.LoadFromFile(filename);
    Assert(aFile.Count = 4,'Not 4 rows in TMatrix');
    for i := 0 to 3 do
    begin
      aLine.DelimitedText := aFile[i];
      Assert(aLine.Count = 4,'Not 4 columns in TMatrix');
      for j := 0 to 3 do
        M[i+1,j+1] := StrToInt(aLine[j]);
    end;
  finally
    aLine.Free;
    aFile.Free; 
  end;
end;