Java - 找不到逻辑错误

标签 java

所以我有这段代码,提示输入以空格分隔的三角形的两条边和斜边。如果三角形正确,则 main 下面的方法应该返回 true,否则返回 false。

出于某种原因,即使我知道我输入的测量值是直角三角形,它仍然会打印出三角形不是直角三角形。

我一直在尝试检测这段代码中的逻辑错误,有人可以帮忙/叫我出来吗?

import java.util.Scanner;

公共(public)类VerifyRightTriangle { 公共(public)静态无效主(字符串[] args){ 扫描仪 sc = new Scanner(System.in);

    System.out.print("Please enter the two sides and the hypotenuse: ");
    String input = sc.nextLine();

    String[] values = input.split(" ");

    int[] nums = new int[values.length];

    for (int i = 0; i < nums.length; i++) {
        nums[i] = Integer.parseInt(values[i]);
    }

    double s1 = nums[0];
    double s2 = nums[1];
    double hyp = nums[2];

    System.out.printf("Side 1: %.2f Side 2: %.2f Hypotenuse: %.2f\n", s1, s2, hyp);

    boolean result = isRightTriangle(s1, s2, hyp);

    if (result == true) {
        System.out.println("The given triangle is a right triangle.");
    } else if (result == false) {
        System.out.println("The given triangle is not a right triangle.");
    }
}

/**
 * Determine if the triangle is a right triangle or not, given the shorter side, the longer
 * side, and the hypotenuse (in that order), using the Pythagorean theorem.
 * @param s1 the shorter side of the triangle
 * @param s2 the longer side of the triangle
 * @param hyp the hypotenuse of the triangle
 * @return true if triangle is right, false if not
 */

private static boolean isRightTriangle(double s1, double s2, double hyp) {
    double leftSide = s1 * s1 + s2 * s2;
    double rightSide = hyp * hyp;
    if (Math.sqrt(leftSide) == Math.sqrt(rightSide)) {
        return true;
    } else {
        return false;
    }
}

}

最佳答案

浮点计算不精确,这就是数字永远不匹配的原因,尝试使用 BigDecimal而不是

编辑: 再三考虑,因为您已经在解析整数 nums[i] = Integer.parseInt(values[i]);

只需使用 int 代替 double 并且不要使用 Math.sqrt,只需使用 leftSide==rightside

关于Java - 找不到逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12238012/

相关文章:

java - 合并 ArrayList 的两个或多个元素

java - 将 javafx 文本区域写入带有换行符的文本文件

java - FileTranfer(DWR)中Byte[]和InputStream的区别

java - Enum 是 JVM 范围的单例吗?

java - 检测自上次用户与应用程序交互以来的时间

java - 使用 PHP 使用 JSONP 返回对象而不是结果

java - 如何在 JTable 中呈现 JTable?

java - 为什么在运行时找不到公共(public)类?

java - 在 Vertx 和 Java 中使用 CRL 处理证书吊销

java - Grails 或 Play 如何检测更改和热重载类?