gpt4 book ai didi

java - 确定的交点不起作用

转载 作者:行者123 更新时间:2023-12-01 12:16:36 24 4
gpt4 key购买 nike

我有未完成的代码来查找所有垂直线的交点。到目前为止我有这个:

import java.util.Scanner;

public class CountSquares {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int lines = scan.nextInt();
scan.nextLine();
double[][] lineMXYC = new double[4][lines]; // stores the slope, and x
// and y co-ordinates and c
// so the line can be
// represented as y = mx + c
double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0;
double slope = 0.0;
for (int i = 0; i < lines; i++) {
String input = scan.nextLine();
String[] arrayOfInput = input.split(" ");
x1 = Integer.parseInt(arrayOfInput[0]);
y1 = Integer.parseInt(arrayOfInput[1]);
x2 = Integer.parseInt(arrayOfInput[2]);
y2 = Integer.parseInt(arrayOfInput[3]);
if (x1 == x2)
slope = Double.POSITIVE_INFINITY;
else
slope = (y2 - y1) / (x2 - x1);
lineMXYC[0][i] = slope;
lineMXYC[1][i] = x1;
lineMXYC[2][i] = y1;
lineMXYC[3][i] = y1 - (slope * x1);

}

for (int j = 0; j < lines - 1; j++) { //sorts the array by slopes
if (lineMXYC[0][j] > lineMXYC[0][j + 1]) {
double TEMP = lineMXYC[0][j + 1];
lineMXYC[0][j + 1] = lineMXYC[0][j];
lineMXYC[0][j] = TEMP;
}
}
double[] pointsOfIntersectionX = new double[(int) (lines * lines / 4) + 1]; //max number of points there can be
double[] pointsOfIntersectionY = new double[(int) (lines * lines / 4) + 1];

int count = 0;
for (int k = 0; k < lines; k++) {
for (int n = k; n < lines; n++) {
System.out.println(n + " " + k);
if (1 / lineMXYC[0][k] == -lineMXYC[0][n]) {
double m1 = lineMXYC[0][k];
double m2 = lineMXYC[0][n];
double c1 = lineMXYC[3][k];
double c2 = lineMXYC[3][n];
System.out.println("m1: "+m1);
System.out.println("m2: "+m2);
System.out.println("c1: "+c1);
System.out.println("c2: "+c2);
pointsOfIntersectionX[count] = (c1 - c2) / (m2 - m1); //determinate to find x co-ordinate
pointsOfIntersectionY[count] = (m2 * c1 - m1 * c2)
/ (m2 - m1);
System.out.println("The lines intersect at: ("
+ pointsOfIntersectionX[count] + ", "
+ pointsOfIntersectionY[count] + ")");
count++;
}
}
}

scan.close();
}
}

这将获取行数,然后每行上用空格分隔两个点。如果我输入

2
3 -1 0 8
3 -1 0 -2

它工作正常,找到了点 (3, -1)但是,如果我反转相同的值

2
3 -1 0 -2
3 -1 0 8

它给了我 (-3.0, 6.999999999999999) 这是错误的

代码出了什么问题?我无法确定问题出在哪里。

最佳答案

按斜率排序可能会在您的版本中混合您的输入数据。如果要交换行,请交换所有行数据:

    for (int j = 0; j < lines - 1; j++) {  //sorts the array by slopes
if (lineMXYC[0][j] > lineMXYC[0][j + 1]) {
for (int i = 0; i < 4; i++) {
double TEMP = lineMXYC[i][j + 1];
lineMXYC[i][j + 1] = lineMXYC[i][j];
lineMXYC[i][j] = TEMP;
}
}
}

如果我可以给你一个建议:

  1. 创建一个单独的 Line 类以实现更好的设计
  2. 实现比较方法或行比较器
  3. 使用某种排序算法,您使用的算法对于更多行将无法正确排序,例如请参阅Java Tutorials

关于java - 确定的交点不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26960223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com