gpt4 book ai didi

java - 在 BlueJ 中使用负无穷大(垂直)斜率

转载 作者:行者123 更新时间:2023-12-02 04:22:09 42 4
gpt4 key购买 nike

我的代码中的所有内容终于看起来都是正确的。我只是遇到了一些棘手的问题。

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

例如,正斜率输出如下所示:

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

垂直行业看起来像:

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");
}
}

最佳答案

您可以明确检查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");

关于java - 在 BlueJ 中使用负无穷大(垂直)斜率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32642726/

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