gpt4 book ai didi

java - Java中如何防止四舍五入到零

转载 作者:行者123 更新时间:2023-12-02 09:30:20 24 4
gpt4 key购买 nike

我正在制作一个模拟此视频中显示的风车动画的处理草图:3Blue1Brown Windmill Problem然而,我遇到了一个问题,我的浮点值在不应该的情况下被舍入为零。例如,我可以使用以下行: float ratio= (520-581)/(158-87)这应该给出 -0.859 的结果,但它只给出 0.0。我知道由于 float 的工作原理, float 通常会存在一定程度的不准确性,但这似乎很极端。我做错了什么,该如何解决?

以下是感兴趣的人的完整代码片段:

void detectCollision(ArrayList<Point> points){
for(Point point : points){
int x1 = rotationalPoint[0];
int y1 = rotationalPoint[1];
int x2 = point.get()[0];
int y2 = point.get()[1];

//skips the point if it's the same as the pivot point
if(x2 != x1 && y2 != y1){
//calculate the angle from the pivot point to a given point
float theta = atan((y2-y1)/(x2-x1));

println("Theta Before: " + degrees(theta));
/* These two lines compensate for the fact that atan as a range from PI/2 to -PI/2
they give the atan function a range from 0 to 2PI
*/
if(x2-x1 < 0) theta += PI;
if(x2-x1 > 0 && y2-y1 < 0) theta = 2*PI-abs(theta);

//some lines to help debug
println("P1: " + x1 + ", " + y1 + " P2: " + x2 + ", " + y2);
println("Theta: " + degrees(theta) + " Angle: " + degrees(angle));

/*checks to see if the current line's angle is close to the angle from the pivot point to the given point
if it is then it will make the given point the new pivot point
*/
if(angle<theta+rotationRate/2 && angle > theta-rotationRate/2){
this.rotationalPoint[0] = x2;
this.rotationalPoint[1] = y2;
}
}
}
}

感谢您的帮助!

最佳答案

除法将整数值作为参数,因此,它执行不带浮点的“整数除法”。在进行除法之前将您的值解析为 float:

float ratio = (float)(520-581) / (float)(158-87);
System.out.println(ratio);

-0.85915494

祝你好运!

关于java - Java中如何防止四舍五入到零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58037028/

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