38.2 数组引用(数组作为函数的输出参数)
boolroots_quadratic_equation2(float a, float b, float c, float (&roots)[3]) {
//the first element is thenumber 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 true;
}
int main(){
float roots[3];
if(roots_quadratic_equation2(1.0, -3.0, 2.0, roots)) {
for (int i=0;i<(roots[0]+1); i++) {
std::cout<< "roots[" << i << "]=" <<roots[i] << endl;
}
}
}
使用这种方法,可以避免在函数中动态分配内存空间,从而可以避免内存泄漏。