查找数组中数组元素的重复出现?

Finding recurrence of array elements in the array?

本文关键字:数组 数组元素 查找      更新时间:2023-10-16

最近,我开始学习C++。我找到了这个问题,关于找到平均分、最高分和最低分、缺席学生人数以及重复哪些分数。

平均、最低和最高分数以及缺席学生的数量按预期工作。但是,重复的标记未按预期工作。

有问题的案例是案例5。

它在某种程度上有效,但是当我给出输入(1,2,1,2,3 个备用输入(和 (1,2,1,2,1(它忽略其中一个数字/再次打印一些数字。 我不知道该怎么办,因为我的知识有限。该程序有什么解决方案吗?

我试图消除它,但正常(不是备用输入(无法正常工作。

您能否提供一种我可以理解的替代方法?

这是我的代码

#include <iostream>
using namespace std;
int main()
{
int Marks[5], i, high, low, menu;
int absent, extra=0, recurr, rcount=0, z;
int hexa=0,seca ,octa=0;
float average, sum = 0;
for(i=0; i<5; i++)
{
cout<<"Enter no of mark:";
cin>>Marks[i];
}
for(i=0; i<5; i++)
if(Marks[i]!=-1)
{
sum=sum+Marks[i];
extra++;
}
cout<<"Choose your operation you want to perform";
cout<<" n 1.Average marks of the class n 2.Highest Scores in Class n 3.Lowest score in classn 4.No of absent studentn 5.No of recurring element";
cin>>menu;
average=sum/extra;
switch(menu)
{
case 1:
cout<<"Average="<<average;
break;
case 2:
high=Marks[0];
for(i=0; i<5; i++)
if(high<=Marks[i])
high=Marks[i];
cout<<"Highest marks= "<<"n"<<high;
break;
case 3:
if(Marks[i]!=-1)
{
low=Marks[0];
for(i=0; i<5; i++)
if(Marks[i]!=-1)
if(low>=Marks[i])
low=Marks[i];
cout<<"Lowest Marks="<<"n"<<low;
}
break;
case 4:
absent=Marks[0];
for(i=0; i<5; i++)
if(Marks[i]==-1) //if -1 is entered it is counted as absent
cout<<"Student not"<<i+1<<"twas abesnt for the exam";
break;
case 5:
//Here is the function that is giving me problem
for(seca=0; seca<5; seca++)
{
recurr=Marks[hexa];
for(i=0; i<5; i++)
if(recurr==Marks[i])
{
rcount++;
z=rcount;
if(z==2)
octa++;
if(octa>2)
octa--;
}
hexa++;
if(z<2)
cout<<"Number "<<recurr<<"is repeated "<<z<<" timesn";
if((octa>1)&&(octa<5))
{
cout<<"Number "<<recurr<<"is repeated "<<z<<" timesn";
octa=0;
}
rcount=0;
}
break;
default:
cout<<"Choose a valid option!!";
}
return 0;
}

据我说,你应该先对它进行排序,然后你会发现很容易计算出现次数。由于您不熟悉C++我建议您使用一种称为气泡排序的排序技术,这对您来说很容易:

for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}

现在排序后,如果您仍然发现一些错误或疑问,请回复,或者如果您没有获得该方法,我将进一步解释:)