Public Class Form1
Private Enum PathFollow
上 = 1
下 = 2
左 = 3
右 = 4
End Enum
Private m_Out(,) As Integer
Private Sub FillNum(ByVal StartNum As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal n As Integer, ByVal Follow As PathFollow)
'假如数字已大于边长的平方或边长小于2则结束递归调用
If StartNum >n ^ 2 Or n <2 Then Exit Sub
'判断方向确定数字如何填充入数组
Select Case Follow
Case PathFollow.上
'假如Y坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为左
If Y - 1 >= 0 AndAlso m_Out(X, Y - 1) = 0 Then
Y -= 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.左
End If
Case PathFollow.下
'假如Y坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为右
If Y + 1 <= n - 1 AndAlso m_Out(X, Y + 1) = 0 Then
Y += 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.右
End If
Case PathFollow.左
'假如X坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为下
If X - 1 >= 0 AndAlso m_Out(X - 1, Y) = 0 Then
X -= 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.下
End If
Case PathFollow.右
'假如X坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为上
If X + 1 <= n - 1 AndAlso m_Out(X + 1, Y) = 0 Then
X += 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.上
End If
End Select
'递归调用
Call FillNum(StartNum, X, Y, n, Follow)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Num As Integer
Dim i As Integer
Dim j As Integer
Dim s As String = ""
'输入一个整数
Num = Fix(Val(InputBox("请输入一个整数")))
If Num <2 Then
MsgBox("输入的数字不合法,无法完成运算", MsgBoxStyle.Critical, "错误")
Exit Sub
End If
ReDim m_Out(Num, Num)
'调用函数填充数组
Call FillNum(1, 0, -1, Num, PathFollow.下)
'输入数组内容
For i = 0 To Num - 1
For j = 0 To Num - 1
s &= " " &m_Out(j, i)
Next
Debug.Print(s)
s = ""
Next
End Sub
End Class
VB定义为二维数组的方法如下:
1、可以通过双击代码窗口中的任何控件来创建代码框架。
2、然后就可以开始编写定义语句了。
3、如果忘记了如何编写变量类型,可以在AS之后执行系统搜索。
4、然后便可以给他进行赋值或者输出;
5、请注意,无法重复定义相同的变量名称,如下图所示。
6、另外,不能是数字的开头,图片也是错误的。
VB源程序如下:
Option Base 1
Private Sub Command1_Click()
Dim A(5, 5) As Integer, B(5, 5) As Integer
For x = 1 To 5
For y = 1 To 5
A(x, y) = Int(10 + Rnd * 90) '随机产生两位数的整数
Print A(x, y) '输出
Next
Next
For x = 1 To 5
For y = 1 To 5
B(x, y) = A(y, x) '转置
Print B(x, y) '输出
Next
Next
End Sub
程序输出结果如下:
扩展资料:
VB:编写程序,实现如下规律的5*5矩阵存入数组,并输出该数组
Private Sub Command1_Click()
Dim a(1 To 6, 1 To 6) As Integer
For i = 1 To 5
For j = 1 To 5
tmp = 99
If i <tmp Then
tmp = i
End If
If j <tmp Then
tmp = j
End If
If 6 - i <tmp Then
tmp = 6 - i
End If
If 6 - j <tmp Then
tmp = 6 - j
End If
a(i, j) = tmp
Next j
Next i
For i = 1 To 5
For j = 1 To 5
Picture1.Print Tab(j * 5)a(i, j)
Next j
Picture1.Print
Next i
End Sub
程序输出结果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)