我是 java 语言的新手,我很困惑为什么会在这里出错。 这是一段非常短的代码,我似乎对此有心理障碍。 有什么建议吗?
public class Rigidbody {
public boolean checkCircleCollision(float x1,float y1,float size1,float x2,float y2,float size2){
if(Math.sqrt(((x2-x1)^2)+((y2-y1)^2))<=(size1+size2)){
return true;
}
}
}
有谁知道我在这里缺少什么? (这可能真的很明显)。
最佳答案
嗯,首先,you forgot to have an else
clause :
public boolean checkCircleCollision(float x1, float y1, float r1,
float x2, float y2, float r2) {
if (Math.sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2)) <= (r1 + r2)){
return true;
} else {
return false;
}
}
Someone else already pointed out这可以缩短如下:
public boolean checkCircleCollision(float x1, float y1, float r1,
float x2, float y2, float r2) {
return Math.sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2)) <= (r1 + r2);
}
(确保为他们点赞 :-)
但是,您的代码仍然是错误的。
如前所述here , Java 的 ^
运算符用于按位异或,而不是取幂。也许你想要 Math.pow()
?
Returns the value of the first argument raised to the power of the second argument.
public boolean checkCircleCollision(float x1, float y1, float r1,
float x2, float y2, float r2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) <= (r1 + r2);
}
或者,您也可以只使用 Math.hypot
而不是自己滚动!
Returns sqrt(x^2 + y^2) without intermediate overflow or underflow.
public boolean checkCircleCollision(float x1, float y1, float r1,
float x2, float y2, float r2) {
return Math.hypot(x2 - x1, y2 - y1) <= (r1 + r2);
}
关于Java 返回一个 boolean 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083775/