I don't know how to cast to float in Java

I am porting some code from Processing to Java, and one problem that I have encountered is that the precompiler handler turns any duplicates into a float. However, in Eclipse, I had to explicitly state my values ​​as a float. However, I get errors that I don’t understand. For example, you should not put f at the end of this statement to correct a type mismatch (Type mismatch: cannot convert from double to float)?

springing[n] = .05*(.17*(n+1))f; 

And even in simpler statements like this, I get a type mismatch. What am I doing wrong?

  float theta = .01f; 
+4
source share
3 answers

Well, your second statement is true to Java standards, but in your first example, Java is probably trying to prevent you from converting doubles to float due to the loss of precision that the programmer should explicitly request, like this:

 double a = //some double; float b = (float) a; //b will lose some of a precision 
+9
source

According to Java grammar, the suffix f applies only to floating point literals. Your second expression should work. The first, however, is an expression and therefore requires the following:

 springing[n] = (float)(.05*(.17*(n+1))); 
+1
source

In your first example, the suffix f only affects literals, not after the whole expression. So write this in one of these ways (assuming springing is a float []):

 springing[n] = .05f*(.17f*(n+1)); springing[n] = (float)( .05*(.17*(n+1))); 

The first one does the whole calculation (except for the part n+1 ) in float, the second one calculates in double, and then converts only the result to float.

(And in both cases, the bracket between .05 and .17 (and the corresponding one) is usually redundant, since multiplication is associative. This may have some meaning for really large n values, but in these cases you usually need another way to avoid overflow.)

+1
source

Source: https://habr.com/ru/post/1340895/


All Articles