查找重复两次的元素是否打印这些数字的问题我没有得到任何输出

问题描述 投票:0回答:1
#include <stdio.h>

int main() {
    int i, j, count, n, a[100], c[100], k = 0;

    printf("Enter size of array: ");
    scanf("%d", &n);

    printf("Enter elements: ");
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    for (i = 0; i < n - 1; i++) {
        count = 1;

        for (j = i + 1; j < n; j++) {
            if (a[i] == a[j]) {
                count++;
                a[j] = -1;
            }
        }

        if (count == 2 && a[i] != -1) {
            c[i] = a[i];
            k++;
        }
    }

    printf("Duplicate elements with their occurrences:\n");
    for (i = 0; i < k; i++) {
        printf("%d ", c[i]);
    }

    return 0;
}

查找重复 2 次的元素是否打印这些数字的问题 我没有得到任何输出 数组问题打印重复 2 次的元素

arrays c sorting arraylist
1个回答
0
投票

c[i] = a[i];
c
中的元素放置在与
a
中找到的元素相同的索引处。

相反,您希望使用

k
的当前值将新值附加到
c
:

if (count == 2 && a[i] != -1) {
    c[k++] = a[i];
}

#include <stdio.h>

int main(void)
{
    int n;
    int a[100] = { 0 };
    int c[100] = { 0 };

    printf("Enter size of array: ");
    scanf("%d", &n);

    printf("Enter elements: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    int k = 0;

    for (int i = 0; i < n - 1; i++) {
        int count = 1;

        for (int j = i + 1; j < n; j++) {
            if (a[i] == a[j]) {
                count++;
                a[j] = -1;
            }
        }

        if (count == 2 && a[i] != -1) {
            c[k++] = a[i];
        }
    }

    printf("Duplicate elements:\n");

    for (int i = 0; i < k; i++) {
        printf("%d ", c[i]);
    }

    putchar('\n');
}
Enter size of array: 5
Enter elements: 1 2 3 3 2
Duplicate elements:
2 3 
© www.soinside.com 2019 - 2024. All rights reserved.