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

前端 未结 3 535
一整个雨季
一整个雨季 2020-12-19 10:52

I\'m porting some code over from Processing to Java, and one issue I\'ve come across is that processing\'s precompiler turns any doubles to floats. In Eclipse however, I\'ve

相关标签:
3条回答
  • 2020-12-19 11:45

    Well, your second statement is correct by Java's standards, but in your first example Java is probably trying to prevent you from converting doubles to floats due to a loss of precision that must be explicitly asked for by the programmer, as so:

    double a = //some double;
    float b = (float) a;  //b will lose some of a's precision
    
    0 讨论(0)
  • 2020-12-19 11:45

    In your first example, the f suffix is only valid directly on literals, not after a whole expression. So write it in either of those ways (assuming springing is a float[]):

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

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

    (And in both cases, the parenthesis between .05 and .17 (and the matching one) is usually superfluous, since multiplication is associative. It might do some difference for really big values of n, but in these cases you would usually want the other way to avoid overflow.)

    0 讨论(0)
  • 2020-12-19 11:53

    According the Java grammar, the f suffix is only applicable to float literals. Your second statement should work. The first however is an expression and therefore requires a cast:

    springing[n] = (float)(.05*(.17*(n+1)));
    
    0 讨论(0)
提交回复
热议问题