怎么编程一元二次方程

时间:2025-01-29 03:36:24 网络游戏

编程求解一元二次方程的基本步骤是:

定义方程的系数 :获取一元二次方程的三个系数 \(a\)、\(b\) 和 \(c\)。

计算判别式:

计算判别式 \(\Delta = b^2 - 4ac\)。

根据判别式的值求解方程

如果 \(\Delta > 0\),方程有两个不同的实数根。

如果 \(\Delta = 0\),方程有一个实数根(重根)。

如果 \(\Delta < 0\),方程有两个共轭复数根。

Python 示例代码

```python

import math

def solve_quadratic(a, b, c):

discriminant = b 2 - 4 * a * c

if discriminant > 0:

root1 = (-b + math.sqrt(discriminant)) / (2 * a)

root2 = (-b - math.sqrt(discriminant)) / (2 * a)

return root1, root2

elif discriminant == 0:

root = -b / (2 * a)

return root,

else:

realPart = -b / (2 * a)

imaginaryPart = math.sqrt(-discriminant) / (2 * a)

return complex(realPart, imaginaryPart), complex(realPart, -imaginaryPart)

示例调用

a, b, c = 1, -3, 2

roots = solve_quadratic(a, b, c)

print(f"The roots are {roots} and {roots}")

```

Java 示例代码

```java

public class QuadraticEquationSolver {

public static void main(String[] args) {

double a = 1, b = -3, c = 2;

double[] roots = solveQuadratic(a, b, c);

System.out.println("The roots are " + roots + " and " + roots);

}

public static double[] solveQuadratic(double a, double b, double c) {

double discriminant = b * b - 4 * a * c;

if (discriminant > 0) {

double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);

double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);

return new double[]{root1, root2};

} else if (discriminant == 0) {

double root = -b / (2 * a);

return new double[]{root, root};

} else {

double realPart = -b / (2 * a);

double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);

return new double[]{complex(realPart, imaginaryPart), complex(realPart, -imaginaryPart)};

}

}

public static double complex(double real, double imaginary) {

return real + imaginary * 1i;

}

}

```

C++ 示例代码