37.1 怎么解一元二次方程?
----------------------------------------------main.cpp ------------------------------------------
main.cpp
float* roots_quadratic_equation(float a, float b, float c) {
//the first element is the number of the real roots, and other elements are the real roots.
float *roots = new float[3];
if (a == 0.0) {
if (b == 0.0) {
roots[0] = 0.0;
}
else {
roots[1] = -c/b;
roots[0] = 1.0;
}
}
else {
float d = b*b - 4*a*c;
if (d < 0.0) {
roots[0] = 0.0;
}
else {
roots[1] = (-b + sqrt(d)) / (2*a);
roots[2] = (-b - sqrt(d)) / (2*a);
roots[0] = 2.0;
}
}
return roots;
}
int main(){
float *r;
r = roots_quadratic_equation(1.0, -3.0, 2.0);
for (int i=0; i<(r[0]+1); i++) {
std::cout << "r[" << i << "]=" << r[i] << endl;
}
}