阵列中出于界限
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:未经治疗的例外: System.IndexOutOfrangeException:索引不在数组的范围之外。 在helloworld.main(system.string [] args)[0x00047] in&lt; 616DCA5EBA0B41F0841F0841FC3BE1BA1BA1BA6DFF5&gt;:0 [错误]致命的未经治疗异常:system.indexoutofrangeException:索引不在数组的边界之外。 在helloworld.main(system.string [] args)[0x00047] in&lt; 616DCA5EBA0B41F0841F0841FC3BE1BA1BA1BA1BA1BA6DFF5&gt;:0
预期O/P:31
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.
at HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at HelloWorld.Main (System.String[] args) [0x00047] in <616dca5eba0b41f0841fc3be1ba6dff5>:0
expected o/p:31
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要添加存储在ARR中的所有值。
您正在尝试将输入值用作索引。
foreach(int j in arr){sum+= j;}
if you want to add all the values stored in arr.
you were trying to use the input value as a index.
foreach(int j in arr){ sum+=j;}