使用数组作为计数器的输出不正确

Incorrect output using array as counter

我正在尝试通过尝试 codeabbey.com 中的问题来自学编程。

我在 this question 上没有得到正确的输出。

Question: Here is an array of length M with numbers in the range 1 ... N, where N is less than or equal to 20. You are to go through it and count how many times each number is encountered.

Input data contain M and N in the first line. The second (rather long) line will contain M numbers separated by spaces. Answer should contain exactly N values, separated by spaces. First should give amount of 1-s, second - amount of 2-s and so on.

数据输入:

10 3

1 2 3 2 3 1 1 1 1 3

正确输出:

5 2 3

我的输出:

7 3 4

你可以查看here

我的代码:

#include <iostream>
using namespace std;

int main()
{
    int arrayLength,range,a;
    cin>>arrayLength>>range;
    int array[20];
    array[20]={0};
    
    for(int i=0; i<arrayLength; i++)
    {   
        cin>>a;
        ++array[a-1];
    }
    for(a=0; a<range; a++)
    {   
    cout<<array[a]<<" ";
    }
    return 0;
}

没有任何错误消息或警告。另外,如果您有任何改进代码的建议,那就太好了。

int array[20];
array[20]={0};

是错误的,因为它使数组未初始化并尝试初始化第 21 个元素(顺便说一句,这是未定义的行为,因为您的数组只有 20 个元素,请记住索引从 0 开始)。使用

int array[20] = {0}; // this will initialize all elements to 0

您的代码将按预期运行。有关 C++ 中聚合初始化的更多详细信息,请参阅 here

array[20]={0}; 将第 21 个元素(不存在)初始化为 0。 所以你必须使用 int array[20] = {0}; 将所有 20 个元素初始化为零。

同样从您的代码来看,您没有将元素存储到数组中。您只是在读取输入时增加相应的计数。如果是这样,将数组初始化为最大限制需要什么。只需根据需要声明数组即可。在你的情况下,

int array[range] = {0};

它将初始化一个包含三个(此处范围 =3)元素的数组。