一元二次方程编程怎么弄

时间:2025-03-05 15:22:37 明星趣事

一元二次方程的一般形式为 `ax^2 + bx + c = 0`,其中 `a`、`b`、`c` 为已知实数,且 `a` 不为 0。求解该方程可以使用求根公式:

\[ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]

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, root

else:

realPart = -b / (2 * a)

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

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

示例方程: x^2 + 2x - 3 = 0

a = 1

b = 2

c = -3

solution = solve_quadratic(a, b, c)

print(f"The solutions are: {solution}")

```

Java

```java

import java.util.Scanner;

public class QuadraticEquationSolver {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("请输入a, b, c的值:");

double a = scanner.nextDouble();

double b = scanner.nextDouble();

double c = scanner.nextDouble();

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);

System.out.println("方程有两个不相等的实数根: " + root1 + " 和 " + root2);

} else if (discriminant == 0) {

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

System.out.println("方程有两个相等的实数根: " + root);

} else {

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

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

System.out.println("方程有两个虚数根: " + realPart + " + " + imaginaryPart + "i 和 " + realPart + " - " + imaginaryPart + "i");

}

}

}

```

C++