You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java三角形判断代码修复请求:无法识别非三角形成立情况

修复三角形判断及直角三角形检测的Java代码

问题分析

  1. 三角形合法性判断逻辑错误:原代码用||(逻辑或)判定两边之和大于第三边,这会导致只要一组两边之和满足条件就判定可构成三角形,但正确规则是任意两边之和都必须大于第三边,需改用&&(逻辑与)。
  2. 浮点数精度问题:直接用==比较浮点数平方和会因浮点运算的精度误差,导致原本的直角三角形被误判,需通过差值绝对值小于极小值来判断近似相等。

修复后的代码

/*This program determines whether a triangle can be formed and whether it is a right triangle or not*/
import java.util.Scanner;

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

        System.out.println("Enter length of line 1: ");
        double a = input.nextDouble();

        System.out.println("Enter length of line 2: ");
        double b = input.nextDouble();

        System.out.println("Enter length of line 3: ");
        double c = input.nextDouble();

        double aSquared = a * a;
        double bSquared = b * b;
        double cSquared = c * c;
        // 定义极小值处理浮点数精度误差
        final double EPSILON = 1e-9;

        // 修正三角形判断条件:三个两边之和大于第三边需同时满足
        if (b + c > a && a + c > b && a + b > c) {
            System.out.println("Lines can form a triangle");
            // 通过差值绝对值判断近似相等,避免精度问题
            if (Math.abs(aSquared - (bSquared + cSquared)) < EPSILON ||
                Math.abs(bSquared - (aSquared + cSquared)) < EPSILON ||
                Math.abs(cSquared - (aSquared + bSquared)) < EPSILON) {
                System.out.println("It is a right triangle");
            } else {
                System.out.println("It is not a right triangle");
            }
        } else {
            System.out.println("Lines cannot form a triangle");
        }
        input.close(); // 关闭输入流,避免资源泄漏
    }
}

修改说明

  • 把三角形判断条件的||替换为&&,确保三个两边之和大于第三边的条件全部满足才判定可构成三角形。
  • 引入EPSILON常量(值为1e-9),用Math.abs()计算平方和的差值,当差值小于该极小值时认为浮点数近似相等,解决精度误差问题。
  • 添加input.close()关闭Scanner,避免资源泄漏。

内容的提问来源于stack exchange,提问作者Raleigh Brecht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:46:17