#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 次的元素
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