简体   繁体   English

数组中的超出边界异常

[英]out of Bound exception in Array

public static void Main(string[] args)
{
int n,sum=0;
n=Convert.ToInt32(Console.ReadLine());
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
    arr[i]=Convert.ToInt32(Console.ReadLine());
}
foreach(int j in arr)
{
    sum+=arr[j];
}
Console.WriteLine(sum);
}
i/p:6
    1
    2
    3
    4
    10
    11

my o/p:Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.我的 o/p:Unhandled Exception: System.IndexOutOfRangeException: Index 超出了数组的范围。 at HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0 [ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.在 HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0 [错误] 致命的未处理异常:System.IndexOutOfRangeException:索引超出了数组的范围。 at HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0在 <616dca5eba0b41f0841fc3be1ba6dff5>:0 中的 HelloWorld.Main (System.String[] args) [0x00047]

expected o/p:31预期o / p:31

if you want to add all the values stored in arr.如果要添加存储在 arr 中的所有值。 you were trying to use the input value as a index.您试图将输入值用作索引。

foreach(int j in arr){ sum+=j;} foreach(int j in arr){ sum+=j;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM