在起始坐标和结束坐标之间生成8个坐标

时间:2017-11-26 11:00:20

标签: java coordinates

好吧,我有两个坐标(红色圆圈) Coordinates

我想生成所有这些果岭。我知道我错了

我使用以下代码

import java.util.ArrayList;
import java.util.List;

public class classA {

    static final int startX = 52760;
    static final int startY = 72440;
    static final int endX = 52520;
    static final int endY = 71896;
    static final List<String> coordinates = new ArrayList<>();

    public static void main(String[] args) 
    {

        calculate(startX, startY, endX, endY);

        coordinates.forEach(System.out::println);
    }

    private static void calculate(int _startX, int _startY, int _endX, int _endY) 
    {

        final int _x = (_startX + _endX) / 2;
        final int _y = (_startY + _endY) / 2;

        coordinates.add(_x + "," + _y);

        if (coordinates.size() != 8)
            calculate(startX, startY, _x, _y);
    }
}

我可以理解,代码会计算&#39; next&#39;的起始值。结束值(以中心为单位)但我无法对其进行配置

输出

wrong

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:2)

说明

在每一步中,您实际上将距离分成两半:

final int _x = (_startX + _endX) / 2;
final int _y = (_startY + _endY) / 2;

这也是你在(开始,中间)等中心看到中间第一个点和下一个点的确切原因。

解决方案

您想要实现的目标称为linear interpolation

你需要将距离分成相等大小的(8 + 1) = 9部分(中间8个部分,总共9个部分)。您可以使用

执行此操作
(end - start) / 9

然后你反复将其添加到start并获得所有积分。或者(为了更精确)使用乘法

start + i * ((end - start) / 9)

接收i - 新点。

此外,您不应使用整数除法,因为它总是向下舍入。要获得准确的结果,您应该转换为double,然后计算结果,最后转换回int以显示值。

代码

代码如下:

private static void calculate(int startX, int startY, int endX, int endY) {
    int amount = 8;

    // Compute the distance to each point
    double wholeDistanceX = endX - startX;
    double distanceX = wholeDistanceX / (amount + 1);

    double wholeDistanceY = endY - startY;
    double distanceY = wholeDistanceY / (amount + 1);

    // Add all new points
    for (int i = 1; i <= amount; i++) {
        // Compute current point
        double currentX = startX + i * distanceX;
        double currentY = startY + i * distanceY;

        // Create the point
        coordinates.add((int) currentX + "," + (int) currentY);
    }
}

请注意,在Java中,您通常不会在变量前面使用_

插图

这是我刚绘制的快速图像,应该有助于理解方程式:

illustration

您会看到第一个和最后一个点位于startend。距离为end - start。距离除9的距离与第一个点到第二个点的距离一样长。因此,第六点位于

start + 6 * ((end - start) / 9)
相关问题