| 本帖最后由 Transpose 于 2023-12-2 09:36 编辑 
 
 [Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode program main
    implicit none
    call magic_square(3)
    call magic_square(5)
    call magic_square(7)
contains
    subroutine magic_square(n)
        integer,intent(in)::n
        integer::a(n,n)
        integer::i
        write(*,"(A,g0)")"n=",n
        a=reshape([(i,i=1,n*n)],shape=[n,n])
        a=cshift(a,[(i,i=-n/2,n/2)],dim=1)
        a=cshift(a,[(i,i=-n/2,n/2)],dim=2)
        do i=1,n
            write(*,"(*(I3))")a(:,i)
        end do
    end subroutine magic_square
end program main
输出
 
 
 [Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode n=3
  8  1  6
  3  5  7
  4  9  2
n=5
 17 24  1  8 15
 23  5  7 14 16
  4  6 13 20 22
 10 12 19 21  3
 11 18 25  2  9
n=7
 30 39 48  1 10 19 28
 38 47  7  9 18 27 29
 46  6  8 17 26 35 37
  5 14 16 25 34 36 45
 13 15 24 33 42 44  4
 21 23 32 41 43  3 12
 22 31 40 49  2 11 20
 
 参考错位补角法https://baike.baidu.com/item/%E5%B9%BB%E6%96%B9/169544
 |