一个C#程序运行报错

来源:百度知道 编辑:UC知道 时间:2024/06/28 00:46:49
using System;
class Test
{
static int Find(int value, int[]array)
{
int i = 0;
while (array[i] != value) {
if (++i > array.Length)
Console.WriteLine( "Can not find");
}
return i;
}
static void Main(){
Console.WriteLine(Find (10, new int[] {6,5, 4, 3, 2, 1}));
}
}

编译可以通过,但是运行就有错:未处理的异常....索引超出了数组界限.

当i=5时,++i=6,再到while里就会因array[6]超出界限而报错。

static int Find(int value, int[]array)
{
int i = 0;
while (i < array.Length)
{
if (array[i] == value)
{
return i;
}
i++;
}
Console.WriteLine( "Can not find");
return -1;
}

如果先++i,会无法检查array[0]的值的。

楼上说的对