Java 浮点计算保持返回0.0
我正在编写一个方法来返回两点之间的点列表。不知何故,斜率(y2-y1)/(x2-x1)始终给我0.0,无论起点和终点位置如何。 方法如下:Java 浮点计算保持返回0.0,java,debugging,math,methods,Java,Debugging,Math,Methods,我正在编写一个方法来返回两点之间的点列表。不知何故,斜率(y2-y1)/(x2-x1)始终给我0.0,无论起点和终点位置如何。 方法如下: public ArrayList<Point> calculatePath(Point startPoint, Point endPoint) { ArrayList<Point> calculatedPath = new ArrayList<>(); int x1 = startPoint
public ArrayList<Point> calculatePath(Point startPoint, Point endPoint) {
ArrayList<Point> calculatedPath = new ArrayList<>();
int x1 = startPoint.x;
int y1 = startPoint.y;
int x2 = endPoint.x;
int y2 = endPoint.y;
System.out.println("Run");
if ((x2 - x1) != 0) {
float ratio = ((y2 - y1) / (x2 - x1));
System.out.println(ratio);
int width = x2 - x1;
for (int i = 0; i < width; i++) {
int x = Math.round(x1 + i);
int y = Math.round(y1 + (ratio * i));
calculatedPath.add(new Point(x, y));
}
} else {
if (y1 < y2) {
while (y1 == y2) {
calculatedPath.add(new Point(x1, y1));
y1++;
}
} else {
while (y1 == y2) {
calculatedPath.add(new Point(x1, y1));
y1--;
}
}
}
return calculatedPath;
}
public ArrayList calculatePath(点起点、点终点){
ArrayList calculatedPath=新的ArrayList();
int x1=起始点.x;
int y1=起始点y;
int x2=端点.x;
int y2=端点y;
System.out.println(“运行”);
如果((x2-x1)!=0){
浮动比率=((y2-y1)/(x2-x1));
系统输出打印项数(比率);
整数宽度=x2-x1;
对于(int i=0;i
有人能指出我做错了什么吗?谢谢请尝试将您的INT转换为浮点数 在计算过程中,您需要铸造至少一个元素以使其浮动:
float ratio = ((float)(y2 - y1) / (float)(x2 - x1));
这是因为:
float a = integer / integer
^^^^^^^^^^^^^^^^^ - The result will be an integer.
Therefore u need to cast at least one of the
to float
这个例子很容易说明:
public static void main(String[] args)
{
float resultWithoutCast = 5 / 3;
float resultWithCast = (float)5 /3 ;
System.out.println(resultWithoutCast);
System.out.println(resultWithCast);
}
它会打印出来
- 1.0
- 1.666
float ratio = ((float)(y2 - y1) / (x2 - x1));
在执行算术时,您需要确保使用的类型允许预期的结果。例如,代码的问题是您正在查找浮点结果,但使用的是
int
——这里的问题是int
只会截断任何浮点
有两种方法可以解决这个问题——正如已经建议的那样,您可以使用cast
float ratio = ((float)(y2 - y1) / (x2 - x1));
或者您可以使用float
变量,这样可以生成更可读的代码,例如
float x1 = (float)startPoint.X;
float y1 = (float)startPoint.Y;
...
float ratio = (y2 - y1) / (x2 - x1);
然而,这会导致更多的铸造
或者,您可以将
点
替换为点F
,并完全取消施法。太棒了!!它起作用了。“这么简单的解决办法,”我花了半个小时才找到