我有一个组成双精度数组,我需要向下舍入并转换为整数,所以我可以将它们用作输出数组中的索引.我刚刚开始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]]++;
Run Code Online (Sandbox Code Playgroud)
但是,我遇到以下错误,我无法解密:
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]
}
^
Run Code Online (Sandbox Code Playgroud)
如果有人能让我知道我哪里出错了,我将不胜感激.
除非您确实想要修改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;
}
Run Code Online (Sandbox Code Playgroud)
当然,你应该真正传递output_array变量的大小,而不是硬编码.