C++
#include <iostream>
#include <cmath>
int main() {
double a, b, c, discriminant, root1, root2;
std::cout << "Enter coefficients a, b and c: ";
std::cin >> a >> b >> c;
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + std::sqrt(discriminant)) / (2 * a);
root2 = (-b - std::sqrt(discriminant)) / (2 * a);
std::cout << "Roots are real and different.\n";
std::cout << "Root1 = " << root1 << "\n";
std::cout << "Root2 = " << root2 << std::endl;
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
std::cout << "Roots are real and same.\n";
std::cout << "Root1 = Root2 = " << root1 << std::endl;
} else {
std::cout << "Roots are complex and different.\n";
// 这里不处理复数根
}
return 0;
}
Python
import cmath
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
# 计算判别式
d = (b**2) - (4*a*c)
# 使用cmath来处理复数
root1 = (-b-cmath.sqrt(d))/(2*a)
root2 = (-b+cmath.sqrt(d))/(2*a)
print("Root1 = {:.2f}+{:.2f}j".format(root1.real, root1.imag))
print("Root2 = {:.2f}+{:.2f}j".format(root2.real, root2.imag))
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a, b, c, discriminant, root1, root2;
System.out.print("Enter coefficients a, b and c: ");
a = scanner.nextDouble();
b = scanner.nextDouble();
c = scanner.nextDouble();
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Roots are real and different.");
System.out.printf("Root1 = %.2f\n", root1);
System.out.printf("Root2 = %.2f\n", root2);
} else if (discriminant == 0) {
root1 = -b / (2 * a);
System.out.println("Roots are real and same.");
System.out.printf("Root1 = Root2 = %.2f\n", root1);
} else {
System.out.println("Roots are complex and different.");
// 这里不处理复数根
}
scanner. Close();
}
}
MySQL
MySQL 并不是为了计算这种数学问题而设计的,但你可以使用 SQL 语句来模拟:
SET @a = 1;
SET @b = -3;
SET @c = 2;
SET @discriminant = POWER(@b, 2) - 4 * @a * @c;
SELECT
CASE
WHEN @discriminant > 0 THEN (-@b + SQRT(@discriminant)) / (2 * @a) AS root1,
(-@b - SQRT(@discriminant)) / (2 * @a) AS root2
WHEN @discriminant = 0 THEN -@b / (2 * @a) AS root1
ELSE 'Roots are