gpt4 book ai didi

java - 距离公式错误

转载 作者:行者123 更新时间:2023-11-29 07:51:35 24 4
gpt4 key购买 nike

我写了一些计算两点之间距离的 Java 代码。出于某种奇怪的原因,它既不收集输入也不查找距离,这就是我想要做的。有人可以帮我吗,这是我的代码:

import java.util.Scanner;

public class Distance
{
static double distance(double x1, double y1, double x2, double y2) {
return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}

public static void main(String[] args) {
double x2, x1, y2, y1;
double distance;

Scanner scan = new Scanner (System.in);
System.out.println("Enter two points: ");
x1 = scan.nextDouble();
y1 = scan.nextDouble();
x2 = scan.nextDouble();
y2 = scan.nextDouble();

distance = distance(x1, y1, x2, y2);
System.out.println("The distance between the two points is " + distance + " .");
}
}

最佳答案

"For some odd reason, it doesn't collect the input nor finds the distance,"

我认为该程序仍在等待您输入积分。您目前可能正在输入:

5.0 4.5 6.7 4.5

都在同一条线上。发生的情况是,在您按下回车键后,扫描仪只读取了一个 double 值。要解决此问题,您必须阅读整行并将其拆分并解析,或者只执行此操作

                System.out.println("Enter x1: ");
x1 = scan.nextDouble();
System.out.println("Enter x2: ");
y1 = scan.nextDouble();
System.out.println("Enter y1: ");
x2 = scan.nextDouble();
System.out.println("Enter y2: ");
y2 = scan.nextDouble();

每次输入后回车

如果你想阅读整行。您需要将输入作为字符串获取,将其拆分,然后解析

                String line = scan.nextLine().trim();
String[] tokens = line.split("\\s+");
x1 = Double.parseDouble(tokens[0]);
x2 = Double.parseDouble(tokens[1]);
y1 = Double.parseDouble(tokens[2]);
y2 = Double.parseDouble(tokens[3]);

关于java - 距离公式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20726223/

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