#define begin { #define end } #define then #define repeat do{ #define until(x) }while(not(x)) #define procedure void #define mod % #define and && #define not ! #define div / #define MAXorder 13 /*** Magic SQUARE(魔方陣)也是暸解array很好的例子 ***/ /*** 魔方陣是指橫的直的斜的加起來都一樣的連續數字方陣***/ /* For example, the following is a Magic Square of order 4: 1 15 14 4 12 6 7 9 8 10 11 5 13 3 2 16 ************************** 偉大的數學家們發現: 四階魔方陣共有880個, 上例只是其中之一 不過三階魔方陣則只有一個! ********************************/ /***** Order 為奇數的Magic Square 可用一簡單方法產生: 在C++課本中有, 第一個說出在第幾頁並 且把原文整題照key in 並follow up 於此的可加期中考3分 ************************************************/ int x[1+MAXorder] [1+MAXorder] ; /*這是 global array , 整個程式都有效*/ procedure outx(int n); procedure oddmagic(int n); int main() begin int i,j,k; int n; char yesno; repeat printf("Generate Magic Square, order=?"); scanf("%d", &n); while(not (( (n>=3) and (n <=MAXorder)) and (n mod 2 == 1)) ) begin /* n 要在範圍內且要奇數我們才做 */ if(not ((n>=3) and (n<= MAXorder)) )then begin printf(" order must be in 3..%d", MAXorder); if(n mod 2 == 0) then printf(", and must be an odd number"); end else begin if(n mod 2 == 0) then printf("Order should be an odd number"); end; printf(", order=?"); scanf("%d", &n); end; oddmagic(n); /* call the procedure oddmagic() */ /* note that the array x is global */ outx(n); /* print out the square x of order n */ printf("One more again(N,Y)?"); scanf(" %c", &yesno); until( (yesno !='y') and (yesno!='Y')); end; procedure oddmagic(int n) begin int row,col,value; int t1,t2; value=0; row= 1-1; /* 第一列的上一列 */ col= (n+1) div 2; /* 中間那格 */ for(t1=1; t1<=n; t1++) begin /* 到下一列 */ row=row+1; if(row > n)then row=1; value=value+1; x[row][col]=value; /* 填下一值 */ for(t2=1; t2<= n-1; t2++) begin /* 到右上角一格 */ row=row-1; if(row < 1)then row=n; col=col+1; if(col > n)then col=1; value=value+1; x[row][col]=value; end; end; end; procedure outx(int n) begin int i,j; for(i=1; i<=n; i++) begin for(j=1; j<=n; j++) begin printf("%5d", x[i][j]); end; printf("\n");; end;/* for i */ end; /*** outx ***/ /******************************************* From: cclo@csie.nctu.edu.tw (想加 RAM 的小孩) 哇咧....這麼好賺!不 key 一下對不起自己.... (page 806) The following is a procedure for constructing an n*n magic square for any odd integer n. Place 1 in the middle of the top row. Then after in- teger k has been placed, move up one row and one column to the right to place the next integer k+1, unless one of the followig occurs: i) If a move takes you above the top row in the jth column, move to the bottom of the jth column and place the integer k+1 there. ii) If a move takes you outside to the right of the square in the ith row, place k+1 in the ith row at the left side. iii) If a move takes you to an already filled square or if you move out of the square at the upper right-hand corner, place k+1 immediately below k. /**********************************************************************/