任意读入10个整数存放到数组a中,统计数组中出现频率最高的数,输出该数及其出现次数。
如果数组中没有重复出现的数,则输出"没有重复出现的数";
如果有多个频率最好的数字,按照输入的先后顺序全部输出,参考下面的程序运行示例。
解题要求
输入10个整数到a数组中,按题目要求统计完成后,先将a数组中数据全部输出(每个数后隔一空格),并将出现频率最高的数及其出现次数输出。格式如下:
数组a中出现频率最高的数是X,出现次数为X
解答如下
#include <stdio.h>
int Count_x(int t[],int size,int x)
{
int count=0;
for(int p=0;p<size;p++)
{
if(t[p]==x)
{
count++;
}
}
return count;
}
int main()
{
int n=10;
int a[10];
int H[n];
int fla=0;
printf("输入10个整数:");
for(int p=0;p<n ;p++ )
{
scanf("%d",&a[p]);
}
printf("a数组:");
for(int p=0;p<n ;p++)
{
printf("%d ",a[p]);
H[p]=Count_x(a,n,a[p]);
if(H[p]>1) fla++;
}
printf("\n");
if(fla==0)
{
printf("没有重复出现的数\n");
}
else
{
int maxH=H[0],maxp=0;
for(int p=1;p<n ;p++ )
{
if(H[p]>maxH)
{
maxH=H[p];
maxp=p;
}
}
int flag[n];
int count_flag=0;
for(int p=0;p<n ;p++ )
{
int out=1;
for(int q=0;q<count_flag;q++)
{
if(flag[q]==a[p])
{
out=0;
break;
}
}
if(H[p]==maxH&&out)
{
printf("数组a中出现频率最高的数是%d,出现次数为%d\n",a[p],H[p]);
flag[count_flag++]=a[p];
}
}
}
return 0;
}
#include <iostream>
#define N1 1000
int b[N1] = { 0 };
int max;
int index = 0;
int i, j, n;
void top(int a[], int size, int N)
{
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
if (a[i] == a[j])
{
b[i]++;
}
}
}
for (int i = 0; i < N; i++)
{
max = b[0];
index = 0;
for (j = 1; j < size; j++)
{
if (max < b[j])
{
max = b[j];
index = j;
}
}
printf("%d,%d\n", a[index], max);
for (j = 0; j < size; j++)
{
if (max == b[j])
{
b[j] = 0;
}
}
}
}
int main()
{
int N = 2;
int a[N1] = { 6,3,3,6,6,-2,3,7,3 };
top(a, 9, N);
return 0;
}
思路:先用for循环遍历数组,采用map的思路,每一个数组元素对应的数组b[],对应a[]相应位置,记录元素在数组a其他位置出现的次数,for循环结束就得到类似于map的一一对应于a的数组b,数组b记录的为数组a中元素出现的元素次数。第二步的思路是当遍历完频率最高的元素次数及元素值,就再用一个for循环置零数组b,然后继续遍历频率次之的元素。
#include <stdio.h>
int main()
{
int inputArray[100], countArray[100];
int elementCount, i, j, count;
printf("Enter Number of Elements in Array\n");
scanf("%d", &elementCount);
printf("Enter %d numbers\n", elementCount);
/* Read array elements */
for(i = 0; i < elementCount; i++) {
scanf("%d", &inputArray[i]);
countArray[i] = -1;
}
/*
* for any element inputArray[i], If countArray[i] = -1,
* that means frequency is not counted for this number yet
* and countArray[i] = 0 means frequency is already
* counted for this number.
*/
for(i = 0; i < elementCount; i++) {
//开始统计inputArray[i]这个元素的出现频率
//至少出现1次
count = 1;
// 值为0表示该数字已经被统计过
if (countArray[i] == 0) {continue;}
for(j = i+1; j < elementCount; j++) {
if(inputArray[i]==inputArray[j]) {
countArray[j] = 0;
count++;
}
}
//记录inputArray[i]出现的频率
countArray[i] = count;
}
/* Print count of each element */
for(i = 0; i<elementCount; i++) {
if(countArray[i] != 0) {
printf("Element %d : Count %d\n", inputArray[i], countArray[i]);
}
}
return 0;
}