为什么我的for循环会跳过数组中的最后一个值

Why does my for loop skip my last values in my array?

本文关键字:数组 最后一个 我的 for 循环 为什么      更新时间:2023-10-16

我的程序应该计算数组中有多少个唯一值。到目前为止,我已经按升序对数组进行了排序(只是为了玩不同的算法),并且正在处理试图计算每个唯一值有多少个值(4,4,4,4,2,3,2,其中2为2,3为1)。

我有一个示例数组,我一直在测试它,它由数字1-10组成,但我的for循环将只到计数8。这可能是一些显而易见的事情,但现在我只是试图找到错误。

受影响的代码片段:

Index =数组的大小

for (int i = 0; i < index; i++)
{
    uniqueness = true;
    for (int l = 0; l < index; l++)
    {
        if (numbers[i] == temporary[l])
        {
            uniqueness = false;
        }
    }
    if (uniqueness)
    {
        temporary[i] = numbers[i];
        number_amount = 0;
        for (int j = 0; j < index; j++)
        {
            if (numbers[j] == temporary[i])
            {
                number_amount++;
            }
        }
        Output(temporary[i], number_amount);
    }
}

/*从数组中找到唯一的数字

int arr = [ 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 7, 9];
int unique[arr.length];
int arrCount = 0;
for (int i = 0; i < arr.length;) {
    bool isUnique = true;
    int currentIndex = i + 1;
    for (int j = i + 1; j < arr.length; j++) {
        if (arr[i] == arr[j]) {
            isUnique = false;
        } else {
            currentIndex = j;
            break;
        }
    }
    i = currentIndex;
    if (isUnique) {  
        unique[arrCount]=arr[i - 1];
        arrCount++;
    }
}
enter code here

对于所有的For循环,它应该是"<= index"而不是"