ht.*_*vit 2 java math debugging methods
我正在编写一种方法来返回2点之间的点数列表.不管怎样,无论startPoint和endPoint位置如何,斜率(y2-y1)/(x2-x1)始终给我0.0.这是方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
谁能指出我做错了什么?谢谢
尝试将你的整体投入到花车中
在你的caluclation过程中,你需要将至少一个元素转换为float:
float ratio = ((float)(y2 - y1) / (float)(x2 - x1));
Run Code Online (Sandbox Code Playgroud)
那是因为:
float a = integer / integer
^^^^^^^^^^^^^^^^^ - The result will be an integer.
Therefore u need to cast at least one of the
to float
Run Code Online (Sandbox Code Playgroud)
这个例子很容易显示:
public static void main(String[] args)
{
float resultWithoutCast = 5 / 3;
float resultWithCast = (float)5 /3 ;
System.out.println(resultWithoutCast);
System.out.println(resultWithCast);
}
Run Code Online (Sandbox Code Playgroud)
它会打印出来
| 归档时间: |
|
| 查看次数: |
1682 次 |
| 最近记录: |