您的位置:首页 > 编程语言 > C语言/C++

Map实现从0~100中随机生成50个数,统计出现的数字最大值和最小值,输出出现最多的次数及对应的数字

2015-01-19 11:13 1196 查看
Map实现从0~100中随机生成50个数,统计出现的数字最大值和最小值,输出出现最多的次数及对应的数字

#include "stdafx.h"

#include <iostream>
#include <map>
#include <fstream>
#include <time.h>

using namespace std;

int main()
{
map<int,int> numCount;

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);
numCount[j]++;
}

int maxNum = 0;
int minNum = 10;
int maxScore = 0;
int minScore = 0;
int showMax = 0;
int showScore = 0;

map<int,int>::iterator iter;
for (iter = numCount.begin(); iter != numCount.end(); iter ++)
{
cout<<iter->first <<"  "<<iter->second<<endl;
if (iter->first > maxNum)
{
maxNum = iter->first;
maxScore = iter->second;
}
if (iter->first < minNum)
{
minNum = iter->first;
minScore = iter->second;
}
if (iter->second > showScore)
{
showScore = iter->second;
showMax = iter->first;
}
}
cout<<"50个随机数中,最小的为"<<minNum<<"出现次数为"<<minScore<<endl;
cout<<"50个随机数中,最大的为"<<maxNum<<"出现次数为"<<maxScore<<endl;
cout<<"50个数中出现最多的是:"<<showScore<<"    出现次数为"<<showScore<<endl;

return 0;
}
运行效果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐