int[] arr1 = new int[10];
int i, n, p = 0, inval;
Console.Write("\n\nInsert New value in the sorted array :\n");
Console.Write("-----------------------------------------\n");
Console.Write("Input the size of array : ");
n = Convert.ToInt32(Console.ReadLine());
/* Stored values into the array*/
Console.Write("Input {0} elements in the array in ascending order:\n", n);
for (i = 0; i < n; i++)
{
Console.Write("element - {0} : ", i);
arr1[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("Input the value to be inserted : ");
inval = Convert.ToInt32(Console.ReadLine());
Console.Write("The exist array list is :\n ");
for (i = 0; i < n; i++)
Console.Write("{0} ", arr1[i]);
/* Determine the position where the new value will be insert.*/
for (i = 0; i < n; i++)
if (inval < arr1[i])
{
p = i;
break;
}
/* move all data at right side of the array */
for (i = n; i >= p; i--)
arr1[i] = arr1[i - 1];
/* insert value at the proper position */
arr1[p] = inval;
Console.Write("\n\nAfter Insert the list is :\n ");
for (i = 0; i <= n; i++)
Console.Write("{0} ", arr1[i]);
Console.Write("\n");
嗨。我正在练习,并在教程中找到了一个示例。 如果我在Array中创建了3个以上的元素并插入其他元素,则会出现错误。但是,如果我创建<= 3个元素并插入,则效果很好。 为什么会发生?您能在这种情况下解释一下吗?
未处理的异常:System.IndexOutOfRangeException:索引为 在数组范围之外。在 C:\ Users \ dell \ documents \ visual中的MyPractice1.Arrays.InsertValue.Run() Studio 2015 \ Projects \ Exercises1 \ MyPractice1 \ Arrays \ InsertValue.cs:line 41在MyPractice1.Program.Main(String [] args)中 C:\ Users \ dell \ documents \ visual studio 2015 \ Projects \ Exercises1 \ MyPractice1 \ Program.cs:第46行