Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

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

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 had to explicitly cast my values as float. Still though, I get errors that I don't understand. For instance, shouldn't putting an f at the end of this statement fix the type mismatch (Type mismatch: cannot convert from double to float)?

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

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

  float theta = .01f;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...