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; }
运行效果为: