哪位大虾帮我做下这道题呀?
输入N
输出N*N的一个魔方阵(各行各列及对角线的和都相等)矩阵
。。。
/* 百度搜索到的 */
#include<stdio.h>
#define N 15
int main(void)
{
int i,j,row,cloum,size,square[N][N],count;
printf("please enter the square size(odd && <=15):\n");
scanf("%d",&size);
while(size%2==0||size>15||size<3)
{
printf("error due to the wrng input!please input it again!\n");
scanf("%d",&size);
}
for(i=0;i<size;i++)
for(j=0;j<size;j++)
square[i][j]=0;
i=0;
j=(size-1)/2;
square[i][j]=1;
for(count=2;count<=size*size;count++)
{
row=i-1<0?(size-1):(i-1);
cloum=j-1<0?(size-1):(j-1);
if(square[row][cloum])
i=(++i)%size;
else
{
i=row;
j=j-1<0?(size-1):(j-1);
}
square[i][j]=count;
}
printf("the %d square is:\n",size);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
printf("%d",square[i][j]);
printf("\n");
}
getchar();
getchar();
return 0;
}
给你一个奇数的:
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
void main(void)
{
int matrix[MAXSIZE][MAXSIZE]; /* the magic square */
int count; /* 1..n*n counting */
int row; /* row index */
int column; /* column index */
int order; /* input order */
char line[100];
do{
system("cls");
printf("\n\t\t\t 奇 数 阶 魔 方 阵(输入1退出程序)");
printf("\n\t\t\t======================================");
printf("\n\n请输入一个小于%d的奇数:",MAXSIZE);
gets(line);
order=atoi(line);
if(order==1)
exit(0);
if (order>MAXSIZE)
printf("\n\t\t*** Error *** 输入的奇数 <%d\n", MAXSIZE);
else if (order%2==0)
printf("\n\t\t*** Error *** 输入的必须是奇数!!!\n");
else
{
row=0; /* start of from the middle */
column=order/2; /* of the first row. */
for (count=1;count<=order*order; count++)
{
matrix[row][column] = count; /* put next # */
if (count % order == 0) /* move down ? */
row++; /* YES, move down one row */
else
{ /* compute next indices */
row = (row == 0) ? order - 1 : row - 1;
column = (column == order-1) ? 0 : column + 1;
}
}
printf("\n\n%d阶魔方阵如下:\n\n", order);
for (row=0; row < order; row++)
{
for (column = 0; column < order; column++)
printf("%4d", matrix[row][column]);
printf("\n");
}
}
system("pause");
}while(order!=1);
}
#include <iostream.h>
#include <iomanip.h>
void magic(int n)
{
//如果是偶数,返回
if((n % 2 == 0) || n <= 1)
return;
int i, j;
//定义两个矩阵,由它们确定输出结果
int **I, **J;
I = new int*[n];
J = new int*[n];
for (i = 0; i < n; i++)
{
I[i] = new int[n];
J[i] = new int[n];
}
//求矩阵I 和 J 的值
int t = (n - 1) / 2;
for(i = 0; i < n; i ++)
I[0][i] = J[0][n-1-i] = (t + i) % n + 1;
for(i = 1; i < n; i ++)
for(j = 0; j < n; j++)
I[i][j] = J[i][n - 1 - j] = I[i - 1][(n - 1 + j)%n];
//输出结果,是N * N 的矩阵
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
cout << n * (I[i][j] - 1) + J[i][j] << ' ';
cout << endl;
}
//释放空间
for(i = 0; i < n; i++)
{
delete []I[i];
delete []J[i];
}
delete []I;
delete []J;
}