计算随机数组中每个数字出现的次数

Count the number of occurences of each number in a random array

我正在编写一个代码,使一个包含 100 个整数的数组充满随机整数。然后它会计算每个整数的出现次数并打印出来,如下所示:

1 occurs 1 time
2 occurs 15 times
3 occurs 9 times
etc...

我的代码的问题是我得到了奇怪的计数。例如,10 的出现次数是 100,但这是不可能的。有时一些整数根本没有被计算在内。

#include <iostream>
#include<ctime>

using namespace std;

int main(){

    int arr[100];

    for(int i = 0; i < 100; i++){
        arr[i] = rand() % (10 - 1 + 1) + 1;
    }

    for(int i = 0; i < 100; i++){
        cout<< arr[i]<<" ";
    }

    int count = 0;

    cout<<" " << endl;

    for(int x = 0; x <= 10; x++){

        for (int i = 0; i < 100; i++)
            if (x == arr[i])
                count++;

        cout<< x << " occurs " << count << " times"<< endl;
    }

    return 0;
}

如果仔细查看输出,您会发现 count 永远不会减少。
这是因为您在循环外声明了它,然后只增加了它。
(因此数组中最大数的“计数”将始终是数组的大小。)

将循环内的计数器移动到它正在计数的 x 的上下文中:

for(int x = 0; x <= 10; x++){
    int count = 0;
    for (int i = 0; i < 100; i++)
    ...

您还可以使用数组来存储原始数组中每个值的计数。

//int count = 0;    // use array instead
int count[10];
for (int i = 0; i < 10; i++) {
    count[i] = 0;
}

cout << " " << endl;

//for (int x = 0; x <= 10; x++) // x cannot be zero due to you add 1 to every random value
for (int x = 1; x <= 10; x++)
{
    for (int i = 0; i < 100; i++)
        if (x == arr[i])
            count[x - 1]++;

    cout << x << " occurs " << count[x - 1] << " times" << endl;
}