c语言求众数和重数问题
时间: 2024-05-04 16:22:03 浏览: 79
求一个数组中的众数和重数,可以采用哈希表的方法。具体步骤如下:
1. 创建一个哈希表,用于存储数组中每个元素出现的次数。
2. 遍历数组,将每个元素作为键值,出现次数作为值存入哈希表中。
3. 遍历哈希表,找到出现次数最多的元素,即为众数。同时记录该元素出现的次数,即为重数。
下面是使用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int main()
{
int n, i, max_num, max_count;
int arr[MAX_SIZE];
int hash[MAX_SIZE] = {0};
printf("Please enter the number of elements: ");
scanf("%d", &n);
printf("Please enter the elements: ");
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
hash[arr[i]]++;
}
max_num = arr[0];
max_count = hash[arr[0]];
for(i = 1; i < n; i++)
{
if(hash[arr[i]] > max_count)
{
max_num = arr[i];
max_count = hash[arr[i]];
}
}
printf("The mode is %d, and its frequency is %d\n", max_num, max_count);
return 0;
}
```
在上面的代码中,我们先创建了一个哈希表 `hash`,用于存储数组中每个元素出现的次数。然后遍历数组 `arr`,将每个元素的出现次数存入哈希表中。接着遍历哈希表,找到出现次数最多的元素,即为众数。最后输出众数和其重数即可。
阅读全文
相关推荐


















