gpt4 book ai didi

Java 返回一个 boolean 错误

转载 作者:搜寻专家 更新时间:2023-11-01 00:59:17 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com