怎么编程求一元二次方程

时间:2025-01-29 03:47:44 网络游戏

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)

示例方程: 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 Text {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("请输入a:");

double a = sc.nextDouble();

System.out.println("请输入b:");

double b = sc.nextDouble();

System.out.println("请输入c:");

double c = sc.nextDouble();

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

if (discriminant > 0) {

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

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

System.out.println("解: x1=" + x1 + " x2=" + x2);

} else if (discriminant == 0) {

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

System.out.println("解: x1=" + x + " x2=" + x);

} else {

System.out.println("此方程无解");

}

}

}

```

C++

```cpp

include

include

void gt(int a, int b, int c) {

double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);

double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);

std::cout << "x1=" << x1 << " x2=" << x2 << std::endl;

}

void eq(int a, int b, int c) {

double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);

double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);

std::cout << "x1=" << x1 << " x2=" << x2 << std::endl;

}

void lt() {

std::cout << "此方程无解" << std::endl;

}

int main() {

int a, b, c;

std::cin >> a >> b >> c;

if ((b * b - 4 * a * c) > 0) {

gt(a, b, c);

} else if ((b * b - 4 * a * c) == 0) {

eq(a, b, c);

} else {

lt();

}

return 0;

}

```

这些代码示例分别展示了如何使用Python、Java和C++求解一元二次方程。每种语言的代码都遵循了相同的基本步骤:

1. 定义一元二次方程的系数a、b和c。

2. 计算判别式Δ(即b² - 4ac)。

3. 根据判别式的值判断方程的根的情况:

如果Δ > 0,方程有两个不同的实数根。

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

如果Δ < 0