检查数组中的值,然后传递给新数组。 C

标签 c arrays

因此给定一个数组:

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/

相关文章:

c - 如何在c中 "clear"数组为较小的数组腾出空间?

c++ - 搜索硬盘中所有文件的最快方法是什么?

c - 变量数组声明

arrays - 从数组开头删除与某个值匹配的尽可能多的元素,直到数组达到指定大小

c++ - C++中如何删除struct数组中的元素

c - 查找具有已知 pid 的进程的 '.text' 部分的范围

c - 我的c程序运行完成后崩溃了

c++ - 打印 char 的二进制格式

arrays - 将字符串 append 到 Matlab 数组

java - 重复for循环练习,初学者需要建议学习