数字范围和显示数字重复c++

range of numbers and show numbers repeat c++

本文关键字:数字 c++ 显示 范围      更新时间:2023-10-16

你可以帮我做一个不同的程序。。它引入了一系列数字(没有限制,您可以重复数字),用于显示每个数字输入的次数。。示例:1 3 4 3 6 1结果:1-2倍3-3x4-1x6-1x

非常感谢。

#include <iostream>
#include <cstdlib>
using namespace std;
int rnd()
{
int iRand = (rand() % 100) + 1;
}
int hundred_random()
{
for (int rCount=0; rCount < 100; ++rCount)
{
cout << rnd() << endl;
}
}
int main()
{
cout << " The list of Hundred random numbers are- " << endl;
hundred_random();
return 0;
}

为了计算每个数字在数字列表中出现的频率,您可以执行以下操作:

#include <iostream>
#include <vector>
#include <map>
#include <cstdlib>

我们需要这些头用于输出、存储数字、存储计数以及生成示例的rand()。

std::vector<int> generate_numbers(int amount, int max_num)
{
std::vector<int> numbers(amount);
for (int i = 0; i < amount; ++i) {
numbers[i] = rand() % max_num + 1;
}
return numbers;
}

生成一组随机数的辅助方法。

std::map<int, int> count_numbers(const std::vector<int> &numbers)
{
// Count numbers
std::map<int, int> counts; // We will store the count in a map for fast lookup (C++11's unordered_map has even faster lookup)
for (size_t i = 0; i < numbers.size(); ++i) { // For each number
counts[numbers[i]]++; // Add 1 to its count
}
return counts;
}

上面的方法计算,这是你问题的本质。对于我们遇到的每一个数字,我们都会增加它的计数。

void print_counts(const std::map<int, int> &counts)
{
for(std::map<int, int>::const_iterator it = counts.begin();
it != counts.end(); ++it) { // For each number stored in the map (this automatically filters those with count 0)
std::cout << it->first << ": " << it->second << std::endl; // Output its count
}
}

最后,介绍了一种显示结果的方法。由于我们从未对任何零次出现的数字进行过操作,因此它们不在映射中,并且将从输出中省略。

int main() {
srand(0); // So that we get the same result every time
std::vector<int> numbers = generate_numbers(10000, 500);
std::map<int, int> counts = count_numbers(numbers);
return 0;
}

把它们放在一起。请参阅此代码运行。