找到给定多边形坐标的长度

时间:2015-01-30 17:00:39

标签: java arrays multidimensional-array geometry

我正在研究一个问题,我需要找到给定多边形坐标的边长。 N是行数,2是列数(x和y坐标),我收集了多维数组中的坐标。

我的想法是收集数组中的x坐标说x1并收集数组中的y坐标说y1。现在找到数组中数字之间的差异并执行距离公式运算。但我无法继续下去。我无法找到使用它的长度,因为答案总是短于实际数字。请帮助我如何找到给定多边形的边长。请在下面找到我的代码:

import java.util.Scanner;


public class Rope {

	public static void main(String[] args) {
		int  N = 1, R=1;
		double AoN=1;
		float d=0 , e=0, f=0, h=0, s=0, length=0, g=0;;
		Scanner in = new Scanner(System.in);
		int[] arr = new int[2];
		System.out.println("Enter number of Nails (N) and Radius of Nail (R) seperated by space: ");
		for (int i=0;i<arr.length;i++) {
			arr[i]=in.nextInt();
		}
		
		if (arr[0]>=1 && arr[0]<=100) {
			N=arr[0]; // N is the number of rows of the multi-dimensional array and rows is fixed to 2 as coordinates are fixed to x and y so 2.
		}
			R=arr[1]; // kindly ignore R as it is used for other purpose.
		
		float[ ][ ] arr1 = new float[N][2];
		System.out.println("Enter Coordinates separated by spaces: ");
		for(int i=0; i<N;i++) {
	    	  for (int j=0;j<2;j++) {
	    		  arr1[i][j]=in.nextFloat();
	    		  //System.out.println(arr1[i][j]);
	    	  	  }	  
	      }
		float[] x = new float[N];
		float[] y = new float[N];
		
		for(int i=0; i<N;i++) {
	    		  x[i] = arr1[i][0];
		}
		for (int j=0;j<N;j++) {
	    		  y[j] = arr1[j][1];
		}
		
		for (int i=0; i<x.length-1;i++) {
			d = (float) (d + (Math.pow((x[i+1] - x[i]),2)));
		}
		
		for (int i=0; i<y.length-1;i++) {
			e = (float) (e + (Math.pow((y[i+1] - y[i]),2)));
		}
		
		
		g = d+e;
		s = (float) Math.sqrt(g);
		sysout(s);
		
in.close();
	}

}

1 个答案:

答案 0 :(得分:1)

因为您的代码中存在逻辑错误。如果您注意到以下部分:

for (int i=0; i<x.length-1;i++) {
            d = (float) (d + (Math.pow((x[i+1] - x[i]),2)));
        }

        for (int i=0; i<y.length-1;i++) {
            e = (float) (e + (Math.pow((y[i+1] - y[i]),2)));
        }

让我们说,

x1-x2 = X1
x2-x3 = X2 

等等

类似地,

y1-y2 = Y1
y2-y3 = Y2 

等等

现在您的代码所做的是计算

    sqrt(X1*X1 + X2*X2.... +Y1*Y1 + Y2*Y2....)

但实际应该做的是,

sqrt(Math.pow((X1-X2),2) + Math.pow(Y1-Y2),2)) + sqrt (Math.pow((X2-X3),2) + Math.pow((Y2-Y3), 2) + ...

因此您的代码会生成错误的值。

您应该尝试以下方法:

for (int i=0; i<x.length-1;i++) {
            float temp;

            temp = (Math.pow((x[i+1] - x[i]),2)) + (Math.pow((y[i+1] - y[i]),2));

            d = (float) (d + sqrt(temp));
        }

// for first and last values /  coordinates w.r.t distance formula
for (int i=x.length-1; i<x.length;i++) {
        float temp;

        temp = (float) ((Math.pow((x[i] - x[0]),2)) + (Math.pow((y[i] - y[0]),2)));

        d = (float) (d + Math.sqrt(temp));
    }   

而不是上面提到的两行。

希望这有帮助!!!

相关问题