用c++代码写求方程 的根,用三个函数分别求当b^2-4ac大于0、等于0、和小于0时的根,并输出结果。从主函数输入a、b、c的值。
时间: 2023-11-29 11:14:17 浏览: 44
jiefangcheng-.rar_c++jiefangcheng_jiefangcheng_solve函数_方程的根_求解函数
以下是C++代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
void roots_positive(double a, double b, double c) {
double root1 = (-b + sqrt(b*b - 4*a*c)) / (2*a);
double root2 = (-b - sqrt(b*b - 4*a*c)) / (2*a);
cout << "The roots are real and different." << endl;
cout << "Root 1: " << root1 << endl;
cout << "Root 2: " << root2 << endl;
}
void roots_zero(double a, double b, double c) {
double root = -b / (2*a);
cout << "The roots are real and equal." << endl;
cout << "Root: " << root << endl;
}
void roots_negative(double a, double b, double c) {
double realPart = -b / (2*a);
double imagPart = sqrt(-b*b + 4*a*c) / (2*a);
cout << "The roots are complex and different." << endl;
cout << "Root 1: " << realPart << " + " << imagPart << "i" << endl;
cout << "Root 2: " << realPart << " - " << imagPart << "i" << endl;
}
int main() {
double a, b, c;
cout << "Enter the coefficients of the quadratic equation: " << endl;
cin >> a >> b >> c;
double d = b*b - 4*a*c;
if (d > 0) {
roots_positive(a, b, c);
} else if (d == 0) {
roots_zero(a, b, c);
} else {
roots_negative(a, b, c);
}
return 0;
}
```
在这个程序中,我们定义了三个函数,分别计算当 $b^2-4ac$ 大于0、等于0、和小于0时的根,并输出结果。主函数中,我们从用户输入获取 $a$、$b$、$c$ 的值,计算 $b^2-4ac$,并根据 $b^2-4ac$ 的值调用不同的函数来计算和输出根。
阅读全文