⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test3.cpp

📁 自己培训的题目——N阶幻方的构造
💻 CPP
字号:
#include "test3.h"


MagicMatrix::MagicMatrix(int m)
{
	N=0;
	row=0;
	line=0;

	for(int i=0; i<m; i++)
		for(int j=0; j<m; j++)
			Matrix[i][j]=0;
}

MagicMatrix::~MagicMatrix()
{
}

void MagicMatrix::FillMatrix(int m)
{
	N=m;

	row=0;
	line=(N+1)/2-1;
	Matrix[row][line]=1;

	for(int d=1; d<=N*N; d++)
	{
		if(row==0&&line==N-1)
		{
			Matrix[row+1][line]=d+1;
			row=row+1;
			line=line;
			continue;
		}

		else if(row==0)
		{
			Matrix[N-1][line+1]=d+1;
			row=N-1;
			line=line+1;
			continue;
		}
		
		else if(line==N-1)
		{
			Matrix[row-1][0]=d+1;
			row=row-1;
			line=0;
			continue;
		}

		else if(Matrix[row-1][line+1]!=0)
		{
			Matrix[row+1][line]=d+1;
			row=row+1;
			line=line;
			continue;
		}

		Matrix[row-1][line+1]=d+1;
		row=row-1;
		line=line+1;
	}
}

void MagicMatrix::DiplayMatrix()
{
	int i,j;

	for(i=0; i<N; i++)
	{
		for(j=0; j<N; j++)
		{
			cout<<Matrix[i][j]<<'\t';
		}
		cout<<'\n'<<endl;
	}
	cout<<'\n';
}

int main()
{
	int m;

	cout<<"Please input the matrix's dimension(an odd number between 1 and 100): "<<'\n'<<endl;
	cin>>m;

	judge: if(m%2==0)
	{
		cout<<"Please input an odd number!"<<endl;
		cin>>m;
		goto judge;
	}
	
	else
	{

		MagicMatrix A(m);

		A.FillMatrix(m);

		cout<<"The last magic square is: "<<'\n'<<endl;
		A.DiplayMatrix();
	}

	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -