C++求一元二次方程的根代码
时间: 2024-10-28 19:15:18 浏览: 17
在C++中,我们可以使用标准库中的`cmath`头文件来处理一元二次方程的解。下面是一个简单的函数,它接收三个参数(a, b, c),分别代表二次方程ax^2 + bx + c = 0的系数,并计算并返回两个可能的根,如果判别式小于零则表示无实数解:
```cpp
#include <iostream>
#include <cmath>
void quadraticRoots(double a, double b, double c) {
double discriminant = b * b - 4 * a * c; // 判别式
if (discriminant > 0) {
double root1 = (-b + sqrt(discriminant)) / (2 * a);
double root2 = (-b - sqrt(discriminant)) / (2 * a);
std::cout << "有两个实数根:root1 = " << root1 << ", root2 = " << root2 << std::endl;
} else if (discriminant == 0) { // 一个实数根
double root = -b / (2 * a);
std::cout << "有一个实数根:root = " << root << std::endl;
} else { // 两个复数根
complex<double> realPart = -b / (2 * a);
complex<double> imaginaryPart = sqrt(-discriminant) / (2 * a);
std::cout << "有两个复数根:(real, imaginary) = (" << realPart << ", " << imaginaryPart << ")" << std::endl;
}
}
int main() {
double a = 1, b = -3, c = 2; // 示例方程x^2 - 3x + 2 = 0
quadraticRoots(a, b, c);
return 0;
}
```
阅读全文