[英]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
我的 o/p:Unhandled Exception: System.IndexOutOfRangeException: Index 超出了數組的范圍。 在 HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0 [錯誤] 致命的未處理異常:System.IndexOutOfRangeException:索引超出了數組的范圍。 在 <616dca5eba0b41f0841fc3be1ba6dff5>:0 中的 HelloWorld.Main (System.String[] args) [0x00047]
預期o / p:31
如果要添加存儲在 arr 中的所有值。 您試圖將輸入值用作索引。
foreach(int j in arr){ sum+=j;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.