danzai 发表于 2023-12-2 01:17:45

Fortran幻方

题目:利用幻方错位补角写法封装子程序,令其可以给出任意奇阶幻方。
有大佬可以解答一下么,实在是写不出来了。

Transpose 发表于 2023-12-2 01:17:46

本帖最后由 Transpose 于 2023-12-2 09:36 编辑

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=)
      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

输出

n=3
816
357
492
n=5
17 2418 15
2357 14 16
46 13 20 22
10 12 19 213
11 18 2529
n=7
30 39 481 10 19 28
38 4779 18 27 29
4668 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 444
21 23 32 41 433 12
22 31 40 492 11 20


参考错位补角法https://baike.baidu.com/item/%E5%B9%BB%E6%96%B9/169544

danzai 发表于 2023-12-2 15:02:21

Transpose 发表于 2023-12-2 09:34
program main
    implicit none
    call magic_square(3)


万分感谢!!!!!太厉害了!!!
页: [1]
查看完整版本: Fortran幻方