From cbcda0637624bbd42e882973312b4c72743ed7da Mon Sep 17 00:00:00 2001 From: aaricee <> Date: Fri, 8 Aug 2025 14:53:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9EFunction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hello.java | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Hello.java b/Hello.java index b8a5adf..64a2282 100644 --- a/Hello.java +++ b/Hello.java @@ -15,4 +15,46 @@ public class Hello { return a+b; } + + /** + * 求解二元一次方程 ax + b = 0 的解 + * @param a 方程系数a,不能为0 + * @param b 方程系数b + * @return 方程的解x + * @throws IllegalArgumentException 当a为0时抛出,因为此时方程无解或有无穷多解 + */ + public static double solveLinearEquation(double a, double b) throws IllegalArgumentException { + if (a == 0) { + throw new IllegalArgumentException("Coefficient 'a' cannot be zero in a linear equation"); + } + return -b / a; + } + + /** + * 求解二元一次方程组: + * a1x + b1y = c1 + * a2x + b2y = c2 + * + * @param a1 第一个方程x的系数 + * @param b1 第一个方程y的系数 + * @param c1 第一个方程常数项 + * @param a2 第二个方程x的系数 + * @param b2 第二个方程y的系数 + * @param c2 第二个方程常数项 + * @return 包含x和y的解的数组,格式为[x, y] + * @throws IllegalArgumentException 当方程组无解或有无穷多解时抛出 + */ + public static double[] solveLinearSystem(double a1, double b1, double c1, + double a2, double b2, double c2) throws IllegalArgumentException { + double determinant = a1 * b2 - a2 * b1; + + if (determinant == 0) { + throw new IllegalArgumentException("The system of equations has no unique solution (either no solution or infinite solutions)"); + } + + double x = (b2 * c1 - b1 * c2) / determinant; + double y = (a1 * c2 - a2 * c1) / determinant; + + return new double[]{x, y}; + } } \ No newline at end of file -- Gitee