问题描述:
所谓众数,就是对于给定的含有N个元素的多重集合,每个元素在S中出现次数最多的成为该元素的重数,多重集合S重的重数最大的元素成为众数。例如:S={1,2,2,2,3,5},则多重集S的众数是2,其重数为3。
算法设计:
可以定义数组来储存数据,之后用数组count来统计数据出现的频数。可以用循环的嵌套两次for循环让数组中的每一个数据和另外的数据比较,相同则对应的count数组的值加1,实现频数统计。然后,可以for循环遍历count数组找到最大值,记下下标,即是众数的下标。代码如下:
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int a[100];
int count[100];
//memset(count, 1, sizeof(count));
int m;
cout << "请输入要输入的数据的个数:";
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> a[i];
count[i] = 1;
}
for (int i = 0; i < m; i++)
{
for (int j = i + 1; j < m; j++)
{
if (a[i] == a[j])
count[i] = count[i] + 1;
}
}
int max = count[0], flag = 0;
for (int k = 1; k < m; k++)
{
if (count[k]>max)
{
max = count[k];
flag = k;
}
}
//cout << a[flag] << " " << count[flag] << endl;
cout << "众数为:";
for (int i = 0; i < m; i++)
{
if (count[flag] == count[i])
cout << a[i] << " ";
}
cout << "重数为:" << count[flag];
return 0;
}
测试如下图:
详情参考:https://blog.youkuaiyun.com/u010077865/article/details/21859895