开发者

Why isn't the below code drawing a line closest to the top left?

public static void main(String args[])
{
    Random r = new Random();

    BufferedImage buf = new BufferedImage(500, 500, BufferedImage.TYPE_3BYTE_BGR);

    Point[] points = new Point[50];

    for(int i = 0; i < points.length; i++)
    {
        points[i] = new Point(r.nextInt(500), r.nextInt(500));
    }

    int b = Color.BLUE.getRGB();
    int w = Color.WHITE.getRGB();
    int g = Color.GREEN.getRGB();


    for(int i = 0; i < points.length; i++)
    {
        buf.setRGB(points[i].x, points[i].y, b);
    }
    Point close = null;
    int max = 5000;

    for(int k = 0; k < points.length; k++)
    {
        Point p = points[k];

        int d = distance(0, 0, p.x, p.y);

        if(d < max)
        {
            close = p;
            d = max;
        }
    }

    Graphics gr = buf.getGraphics();
    gr.drawLine(0, 0, close.x, close.y);

    try
    {
        ImageIO.write(buf, "png", new File("this.png"));
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace开发者_Go百科();
    }
}

public static int distance(int x1, int y1, int x2, int y2)
{
    return (int)Math.sqrt((Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)));
}

I'll get images similar to this, but it's quite obviously not right...and I'm stumped as to why it won't work.

Why isn't the below code drawing a line closest to the top left?


EDIT: What it should look like is this: simply a line from the origin to the nearest blue dot.

Why isn't the below code drawing a line closest to the top left?


You specified

d = max;

in your minimization loop. Instead it should read

max = d;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜