gpt4 book ai didi

c# - 索引超出数组范围 - For 循环

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:50 24 4
gpt4 key购买 nike

注意:这不是重复的,名称和主题类似的问题不能解释这一点。

我正在尝试将数字数组按数字顺序排序,同时折叠任何从前一个递增的数字,因此 921,922,923 变为 921-923。

我写的代码是:

static string FormatReceiptNumbers(int[] numbers)
{
int[] sortedNumbers = numbers;
Array.Sort(sortedNumbers);
string output = "";

//Sort through each element
for(int x = 0; x < sortedNumbers.Length; x++)
{
//Check for Incrementing value
if(x > 0 & sortedNumbers[x] == sortedNumbers[x - 1] - 1)
{
//Check if incrementing value doesn't keep going
for(int y = x; y < sortedNumbers.Length; y++)
{
//check if incrementing values end
if(sortedNumbers[y] != sortedNumbers[y - 1] - 1)
{
output = output + " - " + sortedNumbers[y];
//Check if at end of array
if(y != sortedNumbers.Length)
{
x = y; //Keep going
break;
}
else
{
output.Remove(0, 2);
return output;
}
}
}
}
//if no incrementing value is found add number to input
else
{
output = output + ", " + sortedNumbers[x].ToString();
}
}

//Each addition to the string adds ", " to beginning, remove the first one, and return value
return output.Remove(0, 2);
}

这是我必须使用的:

函数应该变成这样:

892, 893, 894, 895, 906, 920, 845

为此:

845, 892 - 895, 906, 910

这是为了额外信息而执行的方式:

    public static void Main(string[] args)
{
int[] input = {892, 893, 894, 895, 906, 845};
Console.WriteLine(FormatReceiptNumbers(input));
Console.ReadLine();
}

但是,在执行时,它会返回:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Rextester.Program.FormatReceiptNumbers(Int32[] numbers)
at Rextester.Program.Main(String[] args)

注意:我正在使用解释 Rextester 的在线编译器,我很确定这不是问题的原因。

如果有人可以帮助我了解问题的原因,我将不胜感激。我没有看到 x(或 y?)如何越界,因为我已将限制设置为数组长度。提前致谢!

最佳答案

问题出在这一行:

if (x > 0 & sortedNumbers[x] == sortedNumbers[x - 1] - 1)

你应该使用double and 符号&&(即逻辑 and ) 而不是单个 and sign & (binary and)

x = 0 时,您有 sortedNumbers[-1],使数组有越界索引 -> 如果您使用 & 而不是 &&

关于c# - 索引超出数组范围 - For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com