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

标签 c++ arrays 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

您的代码将按预期工作。参见 here有关 C++ 中聚合初始化的更多详细信息。

关于c++ - 使用数组作为计数器的输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30498071/

相关文章:

c - 在 C 中实现/模拟具有 20Mhz 时钟和 1024 预分频器的 16 位计数器

java - Firebase Firestore 分布式计数器 - 找不到要序列化的属性

c++ - 为类中声明的变量定义值

c++ - 在 Visual Studio (2005) 下使用 Makefile 代替解决方案/项目文件

javascript - Ajax - JQuery,数组到查询字符串

arrays - 具有 O(1) 查找和 O(1) 切片的 F# 数组

java - 使用javafx创建一个从数字开始倒数并在0播放音乐的程序

c++ - 静态工厂方法和静态对象内存泄漏

c++ - 使用迭代器调用STL Set中的非静态函数

c++ - 如何在C++中将整数转换为其数字数组