c++
以下是一个C++程序,用于解一元二次方程:
#include <iostream>
#include <cmath>
int main() {
double a, b, c;
std::cout << "请输入二次方程的系数:\n";
std::cout << "a = ";
std::cin >> a;
std::cout << "b = ";
std::cin >> b;
std::cout << "c = ";
std::cin >> c;
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + std::sqrt(discriminant)) / (2 * a);
double root2 = (-b - std::sqrt(discriminant)) / (2 * a);
std::cout << "方程有两个实根:\n";
std::cout << "x1 = " << root1 << "\n";
std::cout << "x2 = " << root2 << "\n";
} else if (discriminant == 0) {
double root = -b / (2 * a);
std::cout << "方程有一个实根:\n";
std::cout << "x = " << root << "\n";
} else {
double realPart = -b / (2 * a);
double imaginaryPart = std::sqrt(-discriminant) / (2 * a);
std::cout << "方程有两个虚根:\n";
std::cout << "x1 = " << realPart << " + " << imaginaryPart << "i" << "\n";
std::cout << "x2 = " << realPart << " - " << imaginaryPart << "i" << "\n";
}
return 0;
}
该程序首先要求用户输入二次方程的系数a、b和c,然后使用判别式来判断方程的根的类型。如果判别式大于0,则方程有两个实根;如果判别式等于0,则方程有一个实根;如果判别式小于0,则方程有两个虚根。根据不同的情况,程序会输出相应的结果。
Python
下面是一个使用Python编写的解一元二次方程的程序:
import math
def solve_quadratic_equation(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant > 0:
x1 = (-b + math.sqrt(discriminant)) / (2*a)
x2 = (-b - math.sqrt(discriminant)) / (2*a)
return x1, x2
elif discriminant == 0:
x = -b / (2*a)
return x
else:
return None
# 测试程序
a = float(input("请输入二次方程的系数a:"))
b = float(input("请输入二次方程的系数b:"))
c = float(input("请输入二次方程的系数c:"))
solutions = solve_quadratic_equation(a, b, c)
if solutions is not None:
if isinstance(solutions, tuple):
print("方程的解为:x1 = %f, x2 = %f" % (solutions[0], solutions[1]))
else:
print("方程的解为:x = %f" % solutions)
else:
print("方程无实数解")
使用该程序,您可以输入二次方程的系数a、b、c,并打印出方程的解。如果方程有两个不相等的实数解,结果会以x1和x2的形式显示;如果方程有一个实数解,结果会以x的形式显示;如果方程没有实数解,则会提示方程无解。
java
以下是一个解一元二次方程的Java程序:
import java.util.Scanner;
public class QuadraticEquationSolver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一元二次方程的三个系数:");
System.out.print("请输入a的值:");
double a = scanner.nextDouble();
System.out.print("请输入b的值:");
double b = scanner.nextDouble();
System.out.print("请输入c的值:");
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 = " + root1 + ", root2 = " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("方程有一个实根:root = " + root);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
System.out.println("方程没有实根,有两个虚根:root1 = " + realPart + " + " + imaginaryPart + "i, root2 = " + realPart + " - " + imaginaryPart + "i");
}
}
}
这个程序首先要求用户输入一元二次方程的三个系数a、b、c,然后计算判别式discriminant。如果判别式大于0,说明方程有两个实根,程序计算并显示这两个实根。如果判别式等于0,说明方程有一个实根,程序计算并显示这个实根。如果判别式小于0,说明方程没有实根,程序计算并显示这两个虚根。