c++求方程的根,用3个函数分别求当大于0、等于0和小于0时的根,并输出结果。要求在主函数输入a、b、c的值,输出方程的根。
时间: 2024-06-13 08:08:09 浏览: 64
以下是C++求解一元二次方程的根的程序,其中使用了三个函数分别求解当b^2-4ac大于0、等于0和小于0时的根,并输出结果:
```c++
#include <iostream>
#include <cmath>
using namespace std;
void roots_greater_than_zero(double a, double b, double c) {
double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
cout << "The roots are real and different." << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
void roots_equal_to_zero(double a, double b, double c) {
double x = -b / (2 * a);
cout << "The roots are real and same." << endl;
cout << "x1 = x2 = " << x << endl;
}
void roots_less_than_zero(double a, double b, double c) {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-b * b + 4 * a * c) / (2 * a);
cout << "The roots are complex and different." << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
}
int main() {
double a, b, c;
cout << "Enter the coefficients a, b and c: ";
cin >> a >> b >> c;
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
roots_greater_than_zero(a, b, c);
} else if (discriminant == 0) {
roots_equal_to_zero(a, b, c);
} else {
roots_less_than_zero(a, b, c);
}
return 0;
}
```
阅读全文