所以基本上我正在尝试编写一个程序,它接受一个整数数组,然后输出最大最小和最小模式以及它发生的次数。 我已经能够找到最大值和最小值以及模式,但我的代码输出的不是最小模式,而是第一个出现的模式。而且我不确定如何处理具有多种模式的输入。 下面我将发布我的代码: #包括 使用命名空间标准;
int main() {
int p,max,min,mode;
cout << "Enter the number of postive integers:"<< endl;
cin >> p;
int pos[p];
cout << "Now enter postive integers!" <<endl;
for(int i=0; i<p; i++) {
cout << "Positive integer " << i+1 << ":";
cin >> pos[i]; }
max =pos[0];
min =pos[0];
for( int i=0; i<p; i++){
if(pos[i]> max) max=pos[i];
if(pos[i]< min) min=pos[i];
}
cout << "Max=" << max << endl;
cout << "Min=" << min << mode= pos[0];
int count[20];
int t=0;
for(int c=0;c<p; c++)
{
for(int d=0;d<p;d++)
{
if(pos[c]==pos[d])
{
count[c]++;
t++;
}
}
int modepos, maxno=count[0];
for(int e=1;e<p;e++)
{
if(maxno<count[e])
{
maxno=count[e];
modepos=e;
}
}
mode=pos[modepos];
if(t==1) {
cout << "There is no positive integer occuring more
than once." << endl;
}
else {
cout <<"The most occuring positive integer is:"<< mode;
cout << "\nIt occurs " << t << " times." << endl;
} return 0; }
可能有更简单和更好的编码方法,但由于我是初学者并且只学过循环/条件/数组/变量声明等我只能在程序中使用它们,任何帮助将不胜感激。
最佳答案
你了解 std::map 吗?使用 std::map 计算数组中元素出现次数的算法非常简单
std::map<long, long > mapFreq;// first: for store value of array pos, second for store value's counter
mapFreq.insert(std::pair<long, long>(pos[0], 1));
for(int i = 1; i < dsize; i++)
{
auto &it = mapFreq.find(pos[i]);
if(it != mapFreq.end())
{
it->second++;
}
else
{
mapFreq.insert(std::pair<long, long>(pos[i], 1));
}
}
然后您可以循环遍历 map Freq 以获得您需要的内容:
int number, counter;
for(auto it : mapFreq)
{
if(it.second < counter)
{
number = it.first;
counter = it.second;
}
}
关于c++ - 在 C++ 中查找最大值、最小值和众数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49290598/