我无法找到正确的逻辑来查找数组中重复元素的数量。我能理解为什么我的逻辑不起作用,但是我无法克服它。
以下是实际问题:
编写一个程序,声明一个大小为
n
的整数数组arr
。先从用户处获取一个正整数n
,然后读取n
个数字并将它们存储在arr
中。检查并打印arr
中重复的数量。结果是数组中所有重复数字的总和。
例如: 如果arr
=[4,3,4,4,3,4,5]
那么重复的次数是6
(其中有4
个重复的数字4
和2
个重复的数字3
)
以下是代码:
#include <stdio.h>
int main() {
int n, i, j, count = 1, p = 0;
printf("Enter the length of array");
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i++) {
printf("Enter a number\n");
scanf("%d", &arr[i]);
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
break;
}
}
if (count != 1) {
p = p + count;
count = 1;
}
}
printf("Number of repetitions are %d", p);
}
对于上述代码,如果我们将数组按照问题中提到的方式进行处理,每当我的代码遇到两个相同的数字4时,它都会将它们都计算在内,因此我的程序最终会多计算一些4。所以我无法找到更好的逻辑来解决这个问题。
(我是初学者,不太了解C语言中使用的高级函数/方法)
break
的逻辑是什么? - Damien