使用BlueJ中的负无穷大(垂直)斜率

时间:2015-09-18 02:04:38

标签: java

我的代码中的所有内容最终都是正确的。我只是遇到了棘手的问题。

如何编写代码,以便当我输入两个点并且斜率为-infinity时,它会被识别,输出显示Vertical而不是Negative Slope

例如,正斜率OUTPUT看起来像:

Enter the x and y coordinates of the first point: 3 -2
Enter the x and y coordinates of the second point: 9 2
Distance: 7.211
Positive Slope

AND垂直看起来像:

Enter the x and y coordinates of the first point: 4 5
Enter the x and y coordinates of the second point: 4 -3
Distance: 8.000
Vertical

现在我的垂直输出看起来像:

Enter the x and y coordinates of the first point: 4 5
Enter the x and y coordinates of the second point: 4 -3
Distance: 8.000
Negative Slope

以下是我的代码现在的样子:

import java.util.Scanner;

public class LineEvaluator
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the x and y coordinates of the first point: ");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();

        System.out.print("Enter the x and y coordinates of the second point: ");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();

        double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
        System.out.printf("Distance: %.3f", distance);

        double slope = ((y2 - y1) / (x2 - x1));

        if(slope > 0)
        System.out.println("Positive Slope");
        else if(slope < 0)
        System.out.println("Negative Slope");
        else if(slope == 0)
        System.out.println("Horizontal");
    }
   }

1 个答案:

答案 0 :(得分:2)

您可以明确检查是否slope == Double.NEGATIVE_INFINITY。您应该对Double.POSITIVE_INFINITY执行相同操作。

    if (slope == Double.NEGATIVE_INFINITY || slope == Double.POSITIVE_INFINITY)
      System.out.println("Vertical");
    else if(slope > 0)
      System.out.println("Positive Slope");
    else if(slope < 0)
      System.out.println("Negative Slope");
    else if(slope == 0)
      System.out.println("Horizontal");

或者您可以使用Double.isInfinite

    if (Double.isInfinite(slope))
      System.out.println("Vertical");
    else if(slope > 0)
      System.out.println("Positive Slope");
    else if(slope < 0)
      System.out.println("Negative Slope");
    else if(slope == 0)
      System.out.println("Horizontal");