如何防止在 Java 中四舍五入为零

How to prevent rounding to zero in Java

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

对于感兴趣的人,这是完整的代码片段:

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;
    }
  }
}
}

感谢您的帮助!

除法将 整数 值作为参数,因此,它执行没有浮点数的 'integer division'。 在进行除法之前将您的值解析为 float

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

-0.85915494

祝你好运!