C++ 实现从0~100中随机生成50个数,统计出现的数字最大值和最小值,输出出现最多的次数及对应的数字
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string.h>
#include <string>
#include <Windows.h>
#include <list>
#include <time.h>
#include <stdlib.h>
using namespace std;
struct IntScore
{
int str;
int score;
};
list<int> plist;
int main()
{
srand((int)time(0));
int j = 0;
for (int i = 0; i < 50; i ++)
{
j = i + (int)(50.0 * rand())/(RAND_MAX + 10.0);
//printf("%d\n",j);
plist.push_back(j); //将随机生成的50个数字存放在队列plist中
}
int maxNum = 0;
int minNum = 10;
int outPerson = 0;
list<int>::iterator ppst;
if (plist.size() == 50)
{
vector<IntScore> mNumVec;
mNumVec.clear();
IntScore tempNum;
for (ppst=plist.begin();ppst!=plist.end();ppst ++)
{
if (*ppst > maxNum)
{
maxNum = *ppst; //50个随机数中的最大值
}
if (*ppst< minNum)
{
minNum = *ppst; //50个随机数中的最小值
}
tempNum.score = 0;
tempNum.str = *ppst;
int findFlag = 0;
for (int nNumVecIndex = 0; nNumVecIndex < mNumVec.size();nNumVecIndex ++)
{
if (tempNum.str == mNumVec[nNumVecIndex].str )
{
mNumVec[nNumVecIndex].score ++;
findFlag = 1;
break;
}
}
if (findFlag == 0)
{
tempNum.score = 1;
mNumVec.push_back(tempNum);
}
}
int maxscore = 0;
int maxscoreIndex;
int maxNumPerson = 0;
for (int nNumVecIndex = 0; nNumVecIndex < mNumVec.size(); nNumVecIndex ++)
{
if (mNumVec[nNumVecIndex].score > maxscore)
{
maxscore = mNumVec[nNumVecIndex].score; //出现最多的那个数字的出现次数
maxscoreIndex = nNumVecIndex;
maxNumPerson = mNumVec[nNumVecIndex].str; //出现最多的那个数字
}
}
if (maxscore < 1)
{
return 0;
}
cout<<"50个随机数中,最小的为"<<minNum<<endl;
cout<<"50个随机数中,最大的为"<<maxNum<<endl;
cout<<"50个数中出现最多的是:"<<maxNumPerson<<" 出现次数为"<<maxscore<<endl;
}
return 0;
}