简体   繁体   中英

Java - 2 Arrays of type float - possible loss of precision found : float required : int

I have 2 Arrays of type float

float[] a = new float [100]; 
float[] b = new float [100]; 

I wish to perform the following

for (int i=0; i<100; i++) {
      a[b[i]]++ // Or a[b[i]] + a[b[i]] + 1;
}

Error possible loss of precision found : float required : int

a[b[i]]

b[i] is a float, so you're trying to use a float as an index to an array. The error message is telling you you're using a float but you need an int.

you can't use a float returned by the "b" array for accessing the "a" array. You have to cast to int.

Indexes of arrays are integers, so you can't use a float to try to access a specific element in an array. You'll either need to change the types of your arrays, or convert your float from b[i] into an int, then use that as the index to access a .

I don't mean to be rude but why?

Regardless you can't reference the index of an array with a floating point value, and that's why you are getting that error. If you really must then you need to cast the value of b[i] to an int.

每个人都已经指出数组索引是整数,但是如果使用int(b[i] ,则可能会产生舍入错误。请尝试先将其舍入,然后进行转换:

a[int(Math.round(b[i])]++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM