c - 如何在 C 中将 double 组转换为整数数组?

标签 c arrays for-loop

我有一个由 double 组成的数组,我需要将其向下舍入并转换为整数,以便我可以将它们用作输出数组中的索引。我刚刚开始 C 编程,但不确定它是如何工作的。到目前为止,我能想到的最好的是:

int create_hist( double input_array[], int count, int output_array[17] ) {
    for ( int i = 0; i < count; i++ ) {
        input_array[i] = int floor(input_array[i]);
        output_array[input_array[i]]++; 

但是我遇到以下错误,我无法破译:

array.c:11:20: error: expected expression before ‘int’
   input_array[i] = int floor(input_array[i]);
                    ^
array.c:12:7: error: array subscript is not an integer
   hist[input_array[i]]++;
       ^
array.c:14:1: error: control reaches end of non-void function [-Werror=return-type]
 }
 ^

如果有人能告诉我我哪里做错了,将不胜感激。

最佳答案

除非您真的想修改 input_array,否则最好将四舍五入的 double 值保存在一个中间变量中,然后访问您的整数数组。无需使用 floor()double 转换为 int 即可。

int create_hist(double input_array[], int count, int output_array[17]) {


    for (int i = 0; i < count; i++) {
        int index = (int)input_array[i];

        if ((index > 16) || (index < 0)) {
            return -1;
        }

        output_array[index]++;
    }

    return 0;
}

当然,您也应该真正将 output_array 的大小作为变量传递,而不是对其进行硬编码。

关于c - 如何在 C 中将 double 组转换为整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594596/

相关文章:

c - 即使我包含了文件,函数的隐式声明?

c - 在 C 中退出二维数组时出现问题

c++ - 使用范围 for 循环而不使用 auto 关键字 c++

javascript - 让 For 循环在第一次迭代时正确执行时陷入困境

C 逐字符读取文件并将其显示在控制台上

c - 如果我使用 "=+"而不是 "+="运算符,是否可以选择让 GCC 警告我?

c - 我想检查数组中的重复值

java - 数组大小与java无关吗?

c++ - 查找整数数组中的一对元素,使得 abs(v[i]-v[j]) 最小化

javascript - button.addEventListener 在嵌套 for 循环中不起作用