C#:添加两个一维数组的方法错误“;并不是所有的代码路径都返回一个值“;
本文关键字:路径 代码 返回 一个 错误 添加 两个 一维数组 方法 并不是 | 更新日期: 2023-09-27 18:25:44
我正在添加两个一维数组,但我在编写的代码中遇到了一个错误:错误:代码中存在未处理的异常。
static void Main()
{
// setup two test arrays
int[] x = new int[] { 2, 4, 6 };
int[] y = new int[] { 3, 6, 9 };
// invoke method and store result
int[] z = AddVectors(x, y);
}
static int[] AddVectors(int[] a, int[] b)
{
// check that both arrays are of the same length
if(a.Length == b.Length ) return null;
// create a new array to store result
int[] c = new int[a.Length];
// carry out addition term by term
for (int i = 0; i <= c.Length; i++)
{
c[i] = a[i] + b[i];
}
// return resulting array
return c;
}
}
您应该检查:
if(a.Length != b.Length ) return null;
PS:试着更简洁、更清楚地说明你的问题是什么。