以下为展示“矩阵行列和相等”的简单示例:
1.用c语言实现的版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#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++语言实现的版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#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" );
}
}
|
运行结果如下图所示:
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/chinawangfei/article/details/52924846