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;
}
}

本文介绍了一种使用C++实现的一元二次方程求解方法。通过给出的系数a、b、c,该算法能够正确计算并返回方程的实数根,包括无实数根的情况。代码中详细展示了如何根据判别式的值来确定根的数量及其具体数值。
1849

被折叠的 条评论
为什么被折叠?



