C需要查找数组中相同最多的数值
时间: 2024-04-15 14:30:00 浏览: 11
在C语言中,你可以使用哈希表(hash table)来记录数组中每个数值出现的次数,然后找到出现次数最多的数值。以下是一个示例代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
void findMostFrequent(int arr[], int size) {
int count[MAX_SIZE] = {0};
int maxCount = 0;
int frequentNum = 0;
for (int i = 0; i < size; i++) {
count[arr[i]]++;
if (count[arr[i]] > maxCount) {
maxCount = count[arr[i]];
frequentNum = arr[i];
}
}
printf("Most frequent number: %d\n", frequentNum);
printf("Frequency: %d\n", maxCount);
}
int main() {
int arr[] = {1, 2, 3, 4, 2, 2, 3, 4, 4, 4};
int size = sizeof(arr) / sizeof(arr[0]);
findMostFrequent(arr, size);
return 0;
}
```
在上述代码中,`findMostFrequent` 函数使用大小为 `MAX_SIZE` 的数组 `count` 来记录每个数值出现的次数。我们遍历给定数组 `arr`,并更新对应数值的计数器。同时,我们使用 `maxCount` 和 `frequentNum` 变量来记录出现次数最多的数值及其频率。
在 `main` 函数中,我们定义了一个示例数组 `arr`,然后调用 `findMostFrequent` 函数来查找并打印出现次数最多的数值及其频率。
运行以上代码,输出结果为:
```
Most frequent number: 4
Frequency: 4
```
这里输出了数组中出现次数最多的数值为4,并且它出现了4次。你可以根据自己的需求对代码进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)