怎么C++编程:输入n个正整数,然后输出出现次数最多的那个数

2024-12-01 13:44:12
推荐回答(4个)
回答1:

#include
#include
using namespace std;

#define NUM 1024

int main(void)
{
// 一次过可输入1024个数字
int data[NUM], n = 0;
int i, j, k;
int times[NUM], visited[NUM], max;

while (cin.peek() != '\n')
{
cin >> data[n];
++n;

if (n == NUM)
break;
}

for (i = 0; i < n; ++i)
{
visited[i] = 0;
times[i] = 1;
}

for (i = 0; i < n; ++i)
{
if (!visited[i])
{
for (j = i + 1; j < n; ++j)
{
if ((data[i] == data[j]) && !visited[j])
{
visited[j] = 1;
++times[i];
}
}
}

visited[i] = 1;
}

max = times[0];
k = 0;

for (i = 1; i < n; ++i)
{
if (times[i] > max)
{
max = times[i];
k = i;
}
}

cout << data[k] << endl;

return 0;
}

回答2:

用空格分隔输入的两个数,找出其中出现次数最多的数,如果有出现最多次数相同的元素则输出最先输入的那个数

#pragma warning(disable: 4786)
#include
#include
#include
#include

using namespace std;

int main()
{
map x;
string temp(" ");
char line[1024];
cin.getline(line, 1024, '\n');
stringstream ss(line);
while(temp != "")
{
ss >> temp;
x[temp]++;
}
map::iterator pos;
int max = 0;
for(map::iterator it = x.begin(); it != x.end(); it++)
{
if(it->second > max)
{
pos = it;
max = it->second;
}
}
cout << pos->first << endl;
return 0;
}

回答3:

指针指向一维数组,输入m个正整数,统计输出现最多的数,和出现次数
#include "stdio.h"
#include "conio.h"
int main()
{
static int m,a[100]={0},n[100],*p,*q;
printf("input m:");
scanf("%d",&m);
for(p=a;pscanf("%d",p);
getchar();
for(p=a;pn[*p]++;
q=p=n;
p++;
while (p{
if(*p>*q)
q=p;
p++;
}
printf("%d %d \n",q-n,*q);
getch();
return 0;
}

回答4:

#include
#include
void main()
{
int *x,n,i,j,y,t,m=0;
printf("输入个数\n");
scanf("%d",&n);
x=(int*)malloc(n*sizeof(int));
for(i=0;ifor(i=0;i{t=0;
for(j=0;jif (x[i]==x[j]) t=t++;
if(t>m) {m=t;y=*x;}
}
printf("次数最多的数%d 次数%d",y,m);
free(x);
}