不是VIP会员,不能显示答案

题目解答

题目:
奇数幻方
对于输入的奇数m, 将 1 到m*m这些自然数填入 m行m列格子中,使每行、每列及对角线的和相等。输出一种填法及这个相等的和。下面的程序中限制m为不超过15的奇数,当输入0时结束程序。如输入3时,程序输出:
8 1 6
3 5 7
4 9 2
Sum=15
const max=15;
var a:array[1..max,1..max] of integer;
   m:integer;
procedure GetAnOddNumberOrZero; 
begin
  repeat
     writeln ('Enter an odd number, no more than 15 ',max,'(0 to stop)');
     readln(m);
   until (m=0) or odd(m) and (m<=max); 
end;
procedure ArrangeMagicMatrix(m:integer);
var row,col,num:integer;
begin
  row:=1; col:= (m+1) div 2 ;
  a[row,col]:=1;
  for num:=2 to m*m do 
  begin
    if (num-1) mod m=0 then row:=row+1 
    else
    begin
      if row=1 then row:=m
	  else dec(row) ;
	  if col=m then col:=1
	  else  inc(col)  ;
    end;
     a[row,col]:=num ;
  end;
end;
procedure Print(m:integer); 
var row,col:integer; 
begin
  for row:=1 to m do
  begin
     for col:=1 to m do write( a[row, col]:5);
  writeln; 
  end;
  writeln ('Sum=', (m*m+1)*m div 2  );
end;
begin
   repeat
      GetAnOddNumberOrZero;
      if m<>0 then
	  begin
	    ArrangeMagicMatrix(m);
		Print(m);
      end;
   until m=0;
end.
考点:
分析:
解答:
评论:
老师: