因此给定一个数组:
input[3] = {0, 0, 0}
此输出:
output[3] = {3, 0 ,0}
代码:
void create_hist(double input[], int num_of_inputs, int output[])
{
int num_to_check = input[0];
int counter = 0;
for (int i = 0; i < num_of_inputs; i++)
{
int j = output[i];
if ((int)input[i] == num_to_check)
{
counter++; /* it was found */
}
output[j] = counter;
}
return;
}
但是如果我有一个 float 组
input[5] = {0.0000, 1.0000, 2.0000, 3.0000, 4.000}
我想将值截断为int
,并计算 0 - 10 范围内的每个整数在输入数组中出现的次数,然后将其输出到:
output[5] = {1, 1, 1, 1, 1}
output[0] = {1} //indicates how many times 0 appeared in the array
或
input[10] = {1.000, 4.000, 5.0000, 2.000, 4.000, 7.000, 9.000, 6.000, 0.000, 0.000}
和输出
output[10] = {2, 1, 1, 0, 2, 1, 1, 1, 0, 1}
output[0] = {2} // this indicates how many times 0 appeared in the first array
谁能告诉我该怎么做?
最佳答案
您不应使用output[i]
作为数组索引。它是一个计数器,而不是您想要计数的值。您应该使用 (int)input[i]
作为索引。
您首先需要将output
的所有元素初始化为0
,然后递增与每个输入的整数部分相对应的元素。
memset(output, 0, sizeof(output[0]) * MAX_INPUT_VALUE);
for (int i = 0; i < num_of_inputs; i++) {
output[(int)input[i]]++;
}
关于检查数组中的值,然后传递给新数组。 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51832767/