嗯,首先,you forgot to have an else
clause:
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);
}
(請務必給予好評他們指出那些出:-)
:
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這可以如下縮短
但是,您的代碼仍然是錯誤的。
如前所述here,Java的^
運算符是針對專有按位OR,而非指數運算。也許你想Math.pow()
?
返回引發第二個參數的權力的第一個參數的值。
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
而不是滾動您自己!
返回sqrt(x^2 + y^2),沒有中間溢出或下溢。
public boolean checkCircleCollision(float x1, float y1, float r1,
float x2, float y2, float r2) {
return Math.hypot(x2 - x1, y2 - y1) <= (r1 + r2);
}
僅供將來參考,如果您發佈實際錯誤而非僅僅說「我是一個錯誤」,它總是更有幫助。看起來好像有幾個人已經發現了這個問題,但是他們可能在錯誤信息的幫助下更快地完成了。 – DaoWen
如果if條件不滿足,那麼你的代碼不會返回布爾值,否則你需要返回其他部分。對於這些類型的編碼,最好使用'flags'。 – exexzian