Untitled

 avatar
unknown
plain_text
10 months ago
1.7 kB
27
Indexable
// Author : 張強笙 B133040016 
// Date : 2025/09/11
// Purpose : 印出 N 階的魔方陣
#include <iostream>
#include <iomanip> 	// 使用 setw 函式 
#include <cmath>	// 使用 pow  函式 
using namespace std;

void magic_square(int n) { 	// 建立魔方陣函式 
	int square[n][n] = {};	// 建立魔方陣陣列 等等要放數字進去 
	int pos_i = 0;			// 等等放數字的座標 pos_i, pos_j
	int pos_j = n/2;
	square[pos_i][pos_j] = 1;
	for(int i = 2; i <= pow(n, 2); i++) { 	// 開始遞迴數字  
		int pos_i_add = (pos_i - 1); 	if(pos_i_add < 0) pos_i_add = n - 1; // pos_i_add, pos_j_add 為要新增數字的座標  
		int pos_j_add = (pos_j - 1);	if(pos_j_add < 0) pos_j_add = n - 1;
		
		if( square[pos_i_add][pos_j_add] == 0  ) { // 檢查要新增數字的座標有沒有放數字,並放入 
			square[pos_i_add][pos_j_add] = i;
			pos_i = pos_i_add;					   // 更新座標為新增數字的座標 
			pos_j = pos_j_add;
		}	
		else {									   // 否則就直接放下面 
			pos_i += 1;  if(pos_i == n) pos_i = 0;
			square[pos_i][pos_j] = i;
		}
	
	}
	
	int max_num = n * n;							// 建立最大數字  
	int width = to_string(max_num).length() + 1;	// 為了避免排版太亂 所以給每個數字固定寬數 而這個固定寬數就式最大的數字的寬度 + 1 
	
	for(int i = 0; i < n; i++) {					// 輸出魔方陣 
		for(int j = 0; j < n; j++) {
			cout << setw(width) << square[i][j];
		}
		cout << endl;
	}
}

int main() {
	int n[5] = {1, 3, 5 ,7 , 9};					// 1, 3, 5, 7, 9 階魔方陣,遞迴用到 
	for(int i = 0; i < 5; i++) {					// 製作各階魔方陣 
		magic_square(n[i]);
		cout << "\n";
	}
	return 0;
} 
Editor is loading...
Leave a Comment