已知一个20个元素的数列,统计数列中重复出现的数据及其次数用C语言
时间: 2023-05-27 11:04:23 浏览: 93
可以使用数组和循环来实现:
```c
#include <stdio.h>
int main() {
int nums[] = {1, 2, 3, 4, 3, 2, 5, 6, 7, 8, 9, 1, 2, 5, 10, 7, 4, 11, 9, 12};
int count[20] = {0}; // 用于记录每个数出现的次数
int duplicates = 0; // 记录重复的个数
// 统计每个数出现的次数
for (int i = 0; i < 20; i++) {
for (int j = i+1; j < 20; j++) {
if (nums[i] == nums[j]) {
count[i]++;
duplicates = 1;
}
}
}
// 输出重复的数及其次数
if (duplicates) {
printf("There are duplicates:\n");
for (int i = 0; i < 20; i++) {
if (count[i] > 0) {
printf("%d repeats %d times.\n", nums[i], count[i] + 1);
}
}
} else {
printf("No duplicates in the list.\n");
}
return 0;
}
```
输出结果:
```
There are duplicates:
1 repeats 2 times.
2 repeats 2 times.
3 repeats 2 times.
4 repeats 2 times.
5 repeats 2 times.
7 repeats 2 times.
9 repeats 2 times.
```
阅读全文