![](/img/trans.png)
[英]Given n positive integer numbers.Print how many numbers occurs at least 2 times in this array on C++
[英]C++ Check how many times there are numbers in the resulting array
我是 C++ 的初学者,有人可以帮助我。 INT 数组。随机。 用 10 到 77 的随机数填充 1000 个整数的数组。检查结果数组中有多少次有数字 10、20、30、40、50、60、70。打印接收到的统计信息。
我看到它是这样的,但我不知道如何计算数组中的数字。
int main()
{
int number[1000];
int countUnits[7];
int count = 0;
srand(time(NULL));
for (int i = 0; i < 1000; i++) {
number[i] = rand() % 68 + 10;
}
for (int i = 0; i < 1000; i++) {
if (number[i] % 10 == 0) {
}
}
}
就像只数一个数字一样开始,除了你有七张支票和七个计数器:
for (int i = 0; i < 1000; i++)
{
if (number[i] == 10)
countUnits[0] += 1;
else if (number[i] == 20)
countUnits[1] += 1;
else if ...
...
}
然后您注意到测试和索引有一个模式,并简化:
for (int i = 0; i < 1000; i++)
{
if (number[i] % 10 == 0)
countUnits[number[i]/10-1] += 1;
}
或者,如果您想让人们对您的 m4d sk1llz 感到困惑:
for (int i = 0; i < 1000; i++)
{
countUnits[number[i]/10-1] += number[i] % 10 == 0;
}
你不远了。 但是您应该首先初始化countUnits
:
int countUnits[7] = {0}; // enough to zero initialize the whole array
然后你可以数:
for (int i = 0; i < 1000; i++) {
if (number[i] % 10 == 0) {
countUnits[number[i] / 10 - 1] += 1;
}
}
这样,您只需扫描一次阵列。
countUnits
的索引必须基于number[i]
的值。
而不是i
像其他人建议的那样。 有了这个(例如)如果索引i
是 934 并且可以被 10 整除,那么结果索引将是 92
这是代码(请原谅printf
):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int
main(void)
{
int number[1000];
int countUnits[7] = { 0 };
srand(time(NULL));
for (int i = 0; i < 1000; i++) {
number[i] = rand() % 68 + 10;
}
for (int i = 0; i < 1000; i++) {
int value = number[i];
if (value % 10 == 0)
countUnits[value / 10 - 1] += 1;
}
for (int i = 0; i < 7; i++)
printf("%d: %d\n",(i + 1) * 10,countUnits[i]);
return 0;
}
由于这是 C++,它应该更容易。 它读起来更像 Python 而不是 C。 在这种情况下,这是一件好事!
我是这样写的:
#include <array>
#include <iostream>
#include <map>
#include <random>
int main()
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(10, 77);
std::array<int, 1000> numbers;
for (auto &number : numbers)
number = distrib(gen);
std::map<int, int> counts;
for (auto const &number : numbers)
if ((number % 10) == 0)
counts[number] ++;
for (auto const &number_count : counts)
{
auto number = number_count.first;
auto count = number_count.second;
std::cout << number << " found " << count
<< (count == 1 ? " time" : " times") << '\n';
}
}
样品 output:
10 found 13 times
20 found 15 times
30 found 13 times
40 found 7 times
50 found 15 times
60 found 9 times
70 found 17 times
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.