以下为展示“矩阵行列和相等”的简单示例:
1.用c语言实现的版本
#include <stdio.h> #include <math.h> void main() { int a[16][16],i,j,n,k; printf("Please input n(1~15,it must be odd.): "); scanf("%d",&n); while(!(n>=1&&n<=15) || n%2==0) { printf("The number is invalid.Please insert again:"); scanf("%d",&n); } //初始化数组 for(i=0; i<=n; ++i) { for(j=0; j<=n; ++j) { a[i][j]=0; } } j = n/2 + 1; a[1][j] = 1; i = 1; for(k=2; k<=n*n; ++k) { i = i - 1; j = j + 1; if(i==0 && j==n+1) //行列都越界 { i = i+2; j = j-1; } else { if(i==0) //行越界 { i = n; } if(j==n+1) //列越界 { j = 1; } } if(a[i][j]==0) //如果里面没数字 { a[i][j] = k; } else //得到新的数值 { i = i + 2; j = j - 1; a[i][j] = k; } } for(i=1; i<=n; ++i) { for(j=1; j<=n; ++j) { printf("%3d", a[i][j]); } printf("\n"); } }
2.用C++语言实现的版本
#include <iostream> #include <math.h> void main() { int a[16][16],i,j,n,k; std::cout<<"Please input n(1~15,it must be odd.): "; std::cin>>n; while(!(n>=1&&n<=15) || n%2==0) { std::cout<<"The number is invalid.Please insert again:"; std::cin>>n; } 初始化数组 for(i=0; i<=n; ++i) { for(j=0; j<=n; ++j) { a[i][j]=0; } } i = 0; j = n/2; a[i][j] = 1; for(k=2; k<=n*n; ++k) { i = i - 1; j = j + 1; if(i<=-1 && j>=n) //行列都越界 { i = 1; j = n - 1; } else { if( i<=-1 ) //行越界 { i = n - 1; } if(j>=n) //列越界 { j = 0; } } if(a[i][j]==0) //如果里面没数字 { a[i][j] = k; } else //得到新的数值 { i = i + 2; j = j - 1; a[i][j] = k; } } for(i=0; i<=n-1; ++i) { for(j=0; j<=n-1; ++j) { printf("%3d", a[i][j]); } printf("\n"); } }
运行结果如下图所示:
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!