阵列中出于界限

发布于 2025-02-12 11:57:51 字数 688 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫多说 2025-02-19 11:57:51

如果要添加存储在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;}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文