在用C ++数组大多数发生的元素? [英] Most occurring element in an array using c++?

查看:133
本文介绍了在用C ++数组大多数发生的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试以下code,以获得最大的一个阵列发生的元素。这是工作良好,但唯一的问题是当有具有出现相同数目的两个或更多元件和等于最发生元件,它只是显示扫描的第一个元素。请帮我度过这一点。

 的#include<的iostream>
使用名字空间std;
诠释的main()
{
    int的I,J,一个[5];
INT流行=一个[0];
INT TEMP = 0,tempCount,数= 1;
COUT<< 输入内容:<< ENDL;
    对于(I = 0; I&小于5;我+ +)
    CIN>> A [1];
        对于(I = 0; I&小于5;我+ +)
    {
        tempCount = 0;
        TEMP = A [1];
        tempCount ++;
            为(J = + 1; J&小于5; J ++)
        {
            如果(一个[J] ==温度)
            {
                tempCount ++;
                如果(tempCount>计数)
                {
                    流行=温度;
                数= tempCount;
                }
            }
        }
    }
COUT<< 大多数发生的元素是:<<流行;
}
 

解决方案

重复洗涤两次,改变两个线路。

 如果(计数> MAXCOUNT)
    MAX_COUNT =计数;
 

 如果(计数== MAXCOUNT)
    COUT<<一[1]  - ;&其中; ENDL;
 

解决方法:

  INT A [5]。
的for(int i = 0;我小于5;我++)
   霉素>>在[I];

INT MAX_COUNT = 0;

的for(int i = 0;我小于5;我++)
{
   诠释计数= 1;
   为(诠释J = i + 1的; J&小于5; J ++)
       如果(A [1] ==一个[J]。)
           算上++;
   如果(计数> MAXCOUNT)
      MAX_COUNT =计数;
}

的for(int i = 0;我小于5;我++)
{
   诠释计数= 1;
   为(诠释J = i + 1的; J&小于5; J ++)
       如果(A [1] ==一个[J]。)
           算上++;
   如果(计数== MAXCOUNT)
       COUT<<一[1]  - ;&其中; ENDL;
}
 

I had tried the following code to get most occurring element in an array. It is working well but the only problem is when there are two or more elements having the same number of occurrence and equal to most occurring element, it just shows the first element scanned. Please help me through this.

#include <iostream>
using namespace std;
int main()
{
    int i,j,a[5];
int popular = a[0];
int temp=0, tempCount, count=1;
cout << "Enter the elements: " << endl;
    for(i=0;i<5;i++)
    cin >> a[i];
        for (i=0;i<5;i++)
    {
        tempCount = 0;
        temp=a[i];
        tempCount++;
            for(j=i+1;j<5;j++)
        {
            if(a[j] == temp)
            {
                tempCount++;
                if(tempCount > count)
                {
                    popular = temp;
                count = tempCount;
                }
            }
        }
    }
cout << "Most occured element is: " <<  popular;
}

解决方案

Repeat solution twice and change two line.

if (count>maxCount)
    max_count = count;

with:

if (count==maxCount)
    cout << a[i] << endl;

Solution:

int a[5];
for (int i=0;i<5;i++)
   cin>>a[i];

int max_count = 0;

for (int i=0;i<5;i++)
{
   int count=1;
   for (int j=i+1;j<5;j++)
       if (a[i]==a[j])
           count++;
   if (count>maxCount)
      max_count = count;
}

for (int i=0;i<5;i++)
{
   int count=1;
   for (int j=i+1;j<5;j++)
       if (a[i]==a[j])
           count++;
   if (count==maxCount)
       cout << a[i] << endl;
}

这篇关于在用C ++数组大多数发生的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆