C语言 查找排序数组中数字计数的程序不工作[已关闭]

oxf4rvwz  于 2023-01-25  发布在  其他
关注(0)|答案(1)|浏览(107)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
5小时前关门了。
Improve this question
程序给出意外输出。

#include <stdio.h>

int main()
{
    int n;
    scanf("%d", &n);
    int arr[n];
    for(int i=0; i<n; i++) {
        scanf("%d", &arr[i]);
    }
    
    for(int j=0; j<n; j++) {
        int count=0;
        for(int k=j; k<n && arr[j]==arr[k]; k++) {
            count++;
            if(arr[j]!=arr[k+1] && (k+1)<n) {
                j=k+1;
            }
        }
        printf("%d occurs %d times", arr[j], count);
    }
    return 0;
}

我试着删除所有可能会得到垃圾值的情况。

ttygqcqt

ttygqcqt1#

printf("%d occurs %d times", arr[j], count);之前,您在j=k+1;处修改了j,因此在执行以下代码行之前不要更新j

for (int j = 0; j < n; j++) {
    int count = 0;
    int k = j;
    for( ; k < n && arr[j] == arr[k]; k++) {
        count++;
    }
    printf("%d occurs %d times\n", arr[j], count);
    j = k - 1;
}

或者:

for (int j = 0; j < n; j++) {
    int count = 0;
    for(int k = arr[j]; j < n && arr[j] == k; j++) {
        count++;
    }
    printf("%d occurs %d times\n", arr[--j], count);
}

相关问题