数字范围和显示数字重复c++
range of numbers and show numbers repeat c++
你可以帮我做一个不同的程序。。它引入了一系列数字(没有限制,您可以重复数字),用于显示每个数字输入的次数。。示例: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;
}
把它们放在一起。请参阅此代码运行。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组