我不知道如何投射到Java浮动 [英] I don't know how to cast to float in Java
问题描述
我将一些代码从Processing移植到Java,我遇到的一个问题是,处理的预编译器将任何双精度变为浮点数。在Eclipse中,我不得不显式地将我的值作为float。尽管如此,我得到的错误,我不明白。例如,不应该在这个语句的末尾添加f来修复类型不匹配(类型不匹配:不能从double转换为
float)?
springing [n] = .05 *(。17 *(n + 1))f;
即使是像这样的简单语句,我得到一个类型不匹配。我做错了什么?
float theta = .01f;那么,你的第二个语句是正确的Java的标准,你的第二个语句是正确的,但在你的第一个例子中,Java可能试图阻止你将双精度转换为浮点数,因为精度的损失必须由程序员明确要求,因此: double a = // some double;
float b =(float)a; // b将会损失一些精度
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;
解决方案 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
这篇关于我不知道如何投射到Java浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!