我有一个矩阵(5x5),其中包含值,例如:
矩阵(1,1)值:'a'
矩阵(1,2)值:'b'
矩阵(2,1)值:'c'
我怎样才能在该矩阵中找到字母'a'并让它输出坐标?
即
用户输入'b'
[在表格中搜索'b']
输出(1,2)
提前致谢
答案 0 :(得分:2)
这很简单:
For i As Integer = 0 To LengthOfMatrix - 1
For y As Integer = 0 To HeightOfMatrix - 1
If Matrix(i, y) = "a" Then Console.Write(i & " " & y & vbCrLf)
Next
Next
假设您将Matrix声明为:
Dim Matrix As Char(,) = {{"a", "b", "c", "d", "e"}, {"a", "b", "c", "d", "e"}, {"a", "b", "c", "d", "e"}, {"a", "b", "c", "d", "e"}, {"a", "b", "c", "d", "e"}}
而LengthOfMatrix和HeightOfMatrix应该是矩阵的维数。它们可以转换为更具动态性的东西,如:
For i As Integer = 0 To Matrix.GetLength(0) - 1 'Get's the length of the first dimension
For y As Integer = 0 To Matrix.GetLength(1) - 1 'Get's the length of the second dimension
If Matrix(i, y) = "a" Then Console.Write(i & " " & y & vbCrLf)
Next
Next
在一个简短的描述中,这个循环所做的就是遍历矩阵的所有元素,并输出符合特定条件的每个元素的坐标(在这种情况下 - 等于'a')。
注意:在大多数编程语言中,数组的索引从0开始,因此矩阵中的第一个元素将位于coords(0,0)。