【问题标题】:How to convert a double array to an integer array in C?如何在C中将双精度数组转换为整数数组?
【发布时间】:2018-04-01 03:44:33
【问题描述】:

我有一个由双精度数组成的数组,我需要向下舍入并转换为整数,以便可以将它们用作输出数组中的索引。我刚刚开始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]
 }
 ^

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

【问题讨论】:

  • 你需要使用括号进行强制转换,你不能使用float作为数组索引,你的函数被定义为返回int但从不返回任何东西。
  • int index = input_array[i] 会将double 隐式转换为int。无需强制转换或floor 函数。
  • 别忘了接受其中一个答案

标签: c arrays for-loop


【解决方案1】:

除非您真的想修改input_array,否则最好将四舍五入的双精度值保存在中间变量中,然后访问您的整数数组。并且无需使用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 的大小作为变量传递,而不是硬编码。

【讨论】:

  • 谢谢,和我最后得到的差不多,但是我忘记回0了。现在好像可以了。
  • 在分配给int 数组之前检查双精度值是大于还是小于INT_MAXINT_MIN 不会有什么坏处。您正在使用的值范围可能不是问题,但double 很容易溢出和int 值。
【解决方案2】:

让我们开始吧:

第一个错误是由于您在声明一个函数。

input_array[i] = int floor(input_array[i]);

注意楼前的int,这不是必需的。应该是

input_array[i] = floor(input_array[i]);

第二个错误是由于您正在使用double in 访问数组元素

output_array[input_array[i]]++;

您应该以其他方式执行此操作或执行以下操作:

output_array[(int) input_array[i]]++;

第三个错误是括号不平衡。

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 2011-01-07
    • 2011-07-07
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多