我正在尝试通过尝试来自 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/