如何在Java中防止四舍五入?

时间:2019-09-21 03:23:49

标签: java floating-point processing

我正在处理一个模拟该视频中显示的风车动画的处理草图: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;
    }
  }
}
}

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

除法将 Integer 值用作参数,因此,它执行了没有浮点数的“整数除法”。 在进行除法之前,将您的值解析为 float

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

-0.85915494

祝你好运!