【问题标题】:Magic Square FreePascal魔方 FreePascal
【发布时间】:2013-04-07 22:00:54
【问题描述】:

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

我必须从文件中读取正方形。

魔方 - 所有行、所有列和两条对角线之和必须相等。

程序显示正确答案,但这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.

【问题讨论】:

  • 事实上,您可以尝试将循环中的readln 替换为read,然后像这样从命令行运行您的程序:yourprogram < inputfile(您可能还需要获取去掉最后的readln;。但是,如果这是一个家庭作业,那么您可能需要使用专用数据类型在代码中打开该文件。

标签: pascal freepascal magic-square


【解决方案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;

【讨论】:

  • 我还没试过,因为我的电脑坏了。我试过了会尽快回复的。
  • Error: Identifier not found "TStringList"Error: Identifier not found "try"
  • TStringListclassesh.inc中声明。
  • 在你的使用声明之后插入这一行,{$i classesh.inc}
  • 好的,然后试试uses Classes,SysUtils;。见TString_List-TString_Tutorial
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多