我是这样做的:
int main()
{
int mode,modecount2,modecount1;
bool is_nomode=false;
vector<int> numbers = { 15,43,25,25,25,25,16,14,93,93,58,14,55,55,55,64,14,43,14,25,15,56,78,13,15,29,14,14,16 };
sort(numbers);
//If you uncomment the following part, you can see the sorted list of above numbers
//for (int i = 0; i < numbers.size(); ++i) std::cout << numbers[i] << '\n';
//keep_window_open();
mode = numbers[0];
modecount1 = 0;
modecount2 = 1; //Obviously any number exists at least once!
for (int i = 1; i < numbers.size(); ++i) {
if(numbers[i]==numbers[i-1]) ++modecount2;
else {
if (modecount2 > modecount1) {
mode = numbers[i - 1];
modecount1 = modecount2;
}
else if (i != 1 && modecount2 == modecount1) { std::cout << "No mode!\n"; is_nomode = true; break; }
modecount2 = 1;
}
}
if(!is_nomode) std::cout << "Mode of these numbers is: " << mode << std::endl;
keep_window_open();
您也可以在数字列表中添加另外 25 个,看看如果两个数字出现相同的情况会发生什么!我希望它有所帮助。