![]() ![]() |
|
C++实例奇数阶魔方阵问题 | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/11/1 20:41:22 文章录入:杜斌 责任编辑:杜斌 | |
|
|
8 1 6 3 5 7 4 9 2 n阶魔方阵的构造方法为: 1> 首先把1放在顶行的正中间,然后把后继数按顺序放置在右上斜的对角线上; 2> 当到达顶行时,下一个数放到底行,好像它在顶行的上面; 3> 当到达最右列时,下一个数放在最左端列,好像它仅靠在右端列的右方; 4> 当到达的位置已经填好数时,考试大提示:或到达右上角的位置时,下一个数就放在刚填写的位置的正下方。 C++函数如下: /*奇数阶魔方阵问题*/ #include<iostream> using namespace std; const int MAX=50; void main() { int matrix[MAX][MAX]; int count; int row; int column; int order; cout<<"请输入阶数:"; cin>>order; if(order%2==0) { cout<<"阶数必须是一个奇数,请重新输入!"<<endl; } else { row=0; column=order/2; for(count=1;count<=order*order;count++) { matrix[row][column] = count; if (count % order == 0) { row++; } else { row = (row == 0) ? order - 1 : row - 1; column = (column == order-1) ? 0 : column + 1; } } for (row = 0; row < order; row++) { for (column = 0; column < order; column++) { cout<<"\t"<<matrix[row][column]; } cout<<endl; } } } 程序运行打印出相应的n阶魔方阵. |
|
![]() ![]() |