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();
}
}
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)));
}
我会得到与此相似的图像,但显然不对......而且我很难理解为什么它不起作用。
编辑: 它应该是这样的:只是从原点到最近的蓝点的一条线。
答案 0 :(得分:8)
您指定了
d = max;
在最小化循环中。相反应该阅读
max = d;