我有一个这样的矩阵
13 7 22
101 50 3
我想打印最小的数字。 以下是我的代码:
using System;
class Class1
{ int min(int[,] arr)
{
int small = arr[0, 0];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (small > arr[i, j])
{
small = arr[i, j];
}
}
}
return small;
}
public static void Main()
{
int[,] x;
x = new int[,] { { 13, 7, 22 }, { 101, 50, 3 } };
Class1 obj = new Class1();
Console.WriteLine("Smallest Element : {0}", obj.min(x));
Console.ReadLine();
}
}
抛出错误为
{"Index was outside the bounds of the array."}
预期输出为 3
为什么会出现这个错误?请给我解决方案。
最佳答案
请注意,您可以使用 foreach
遍历多维数组的所有元素,而不必担心索引。
所以写你的 min()
更简单像这样的方法(请注意,我还使用 Math.Min()
来查找两个值中的较小值,而不是编写我自己的 if
来执行此操作):
static int min(int[,] arr)
{
int small = int.MaxValue;
foreach (int n in arr)
small = Math.Min(n, small);
return small;
}
另请注意我是如何初始化 small
的成为最大可能的 int,以避免必须访问数组的第一个值来初始化它。
如果您想使用 Linq 做同样的事情,您可以这样做:
int min = array.Cast<int>().Min();
Cast<int>
的原因需要是因为多维数组只实现非泛型 IEnumerable
而不是通用的 IEnumerable<T>
. See this question for more details .
但是,如果您目前正在学习 C#,那么使用 Linq 是一个高级主题,在这种情况下暂时不用担心!
关于c# - 在矩阵中查找小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45435419/