简体   繁体   English

我不知道如何在Java中进行强制转换

[英]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. 我正在将一些代码从Processing移植到Java,遇到的一个问题是处理的预编译器会将所有double转换为float。 In Eclipse however, I've had to explicitly cast my values as float. 但是,在Eclipse中,我必须将值显式转换为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)? 例如,是否不应该在该语句的末尾加上f来修复类型不匹配(类型不匹配:不能从double转换为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: 嗯,您的第二条语句按照Java的标准是正确的,但是在您的第一个示例中,Java可能试图阻止您将双精度转换为浮点数,因为精度必须由程序员明确要求,如下所示:

double a = //some double;
float b = (float) a;  //b will lose some of a's precision

According the Java grammar, the f suffix is only applicable to float literals. 根据Java语法,后缀f仅适用于浮点文字。 Your second statement should work. 您的第二个语句应该起作用。 The first however is an expression and therefore requires a cast: 但是,第一个是表达式,因此需要强制转换:

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

In your first example, the f suffix is only valid directly on literals, not after a whole expression. 在您的第一个示例中,后缀f仅对文字直接有效,而对整个表达式无效。 So write it in either of those ways (assuming springing is a float[]): 因此,可以使用以下两种方法之一编写它(假设弹跳是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. 第一个以float进行整个计算(除了n+1部分),第二个以double进行计算,然后仅将结果转换为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.) (并且在两种情况下, .05.17 (以及匹配的那个)之间的括号通常都是多余的,因为乘法是关联的。对于n很大的值可能会有所不同,但是在这些情况下,您通常会希望其他避免溢出的方法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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