索引超出范围异常的数组[重复](Index out of range exception on array [duplicate])

编程入门 行业动态 更新时间:2024-10-27 23:31:00
索引超出范围异常的数组[重复](Index out of range exception on array [duplicate])

这个问题在这里已有答案:

什么是IndexOutOfRangeException / ArgumentOutOfRangeException以及如何解决它? 3个答案

我正在尝试反转数组。 这是我的代码:

using System; class Hello { static void Main() { int[] num = new int[] { 1, 2, 3, 4, 5 }; int index = num.Length - 1; int[] newNum = new int[index]; for (int i = 0; i < num.Length; i++) { newNum[i] = num[index]; // error index--; Console.WriteLine(newNum[i]); } Console.ReadLine(); } }

当我运行代码时,控制台打印

5 4 3 2

然后返回一个错误:

IndexOutOfRangeException未处理

在线上:

newNum[i] = num[index];

这行代码有什么问题? 当我在for循环之前打印num[0]它工作正常。

This question already has an answer here:

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it? 4 answers

I'm trying to reverse an array. This is my code:

using System; class Hello { static void Main() { int[] num = new int[] { 1, 2, 3, 4, 5 }; int index = num.Length - 1; int[] newNum = new int[index]; for (int i = 0; i < num.Length; i++) { newNum[i] = num[index]; // error index--; Console.WriteLine(newNum[i]); } Console.ReadLine(); } }

When I run the code, the console prints

5 4 3 2

and then returns an error:

IndexOutOfRangeException was unhandled

on the line:

newNum[i] = num[index];

What's wrong with that line of code? When I print num[0] before that for loop it works fine.

最满意答案

你的新阵列的长度是4.这意味着我将从0到3覆盖

int[] newNum = new int[index];

你的循环将变为i = 4

当我将4你的代码将崩溃。 因为newNum仅支持第3个索引。

这应该是

int[] newNum = new int[index+1];

length of your new array is 4. that's mean I'll cover from 0 to 3

int[] newNum = new int[index];

and your loop will go i=4

when i will 4 your code will collapse. as newNum support only to 3rd index.

this should be

int[] newNum = new int[index+1];

更多推荐

本文发布于:2023-07-16 18:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1132405.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   异常   Index   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!