在c ++中查找Max,Min和Mode

时间:2018-03-15 02:24:45

标签: c++ arrays for-loop

所以基本上我正在尝试编写一个程序,它接受一个整数数组,然后输出Max Min和最小模式以及它出现的次数。 我已经能够找到max和min以及模式,但是我的代码输出的是最先出现的模式,而不是最小模式。我不知道如何使用多种模式处理输入。 下面我将发布我的代码:      #包括       使用namespace std;

   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; }

可能有更简单和更好的方法来编码,但由于我是初学者并且只学习了循环/条件/数组/变量声明等我只能在程序中使用它们,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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));
    }
}

然后您可以根据需要循环浏览地图Freq:

int number, counter;
for(auto it : mapFreq)
{
    if(it.second < counter)
    {
        number = it.first;
        counter = it.second;
    }
}

答案 1 :(得分:0)

也许你可以尝试这样做:

#include <iostream>
#include <algorithm> //for sorting
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[n];
sort(a,a+n);
int b[a[n-1]];
for(int i=0;i<a[n-1];i++) b[i]=0;
for(int i=0;i<n;i++) b[a[i]]++;
cout<<"Largest number = "<<a[n-1]<<endl;
cout<<"Smallest number = "<<a[0]<<endl;
int rep=0;//repetition
int mode=0;
for (int i=0;i<a[n-1];i++){
  if(b[i]>rep){
    rep=b[i];// set times of repetition
    mode=i;// set new mode
  }
}
cout<<"Mode = "<<mode<<endl;
}