Concept
How can PHP pass variables by reference to return multiple quadratic roots?
ComputerScienceOne / Quadratic Roots
"40.2.2. Quadratic Roots Another advantage of passing variables by reference is that we can “return” multiple values with one function call. Functions are limited in that they can only return at most one value. But if we pass multiple parameters by reference, the function can manipulate the contents of them, thereby communicating (though not strictly returning) multiple values. Consider again the problem of computing the roots of a quadratic equation, ax2 + bx + c = 0 using the quadratic formula, x = (−b ± √(b2 − 4ac)) / 2a. Since there are two roots, we may have to write two functions, one for the “plus” root and one for the “minus” root both of which take the coefficients, a, b, c as arguments. However, if we wrote a single function that took the coefficients as parameters by value as well as two other parameters by reference, we could compute both root values, one in each of the by-reference variables.\n\nfunction quadraticRoots($a, $b, $c, &$root1, &$root2) {\n\n$discriminant = sqrt($b*$b - 4*$a*$c);\n\n$root1 = (-$b + $discriminant) / (2*$a);\n\n$root2 = (-$b - $discriminant) / (2*$a);\n\nreturn;\n\n}\n\nBy using pass by reference variables, we avoid multiple functions. Recall that there could be several “bad” inputs to this function. The roots could be complex values, the coefficient a could be zero, etc. In the next chapter, we examine how we can handle these errors."
Related Ideas
- How does PHP compute the roots of a quadratic equation?ComputerScienceOne · Computing Quadratic Roots
- How can pass-by-reference parameters return both roots of a quadratic equation?ComputerScienceOne · Quadratic Roots
- How can a PHP program prompt for the coefficients of a quadratic polynomial?ComputerScienceOne · Computing Quadratic Roots
- How can the return value communicate errors when roots are passed by reference?ComputerScienceOne · Quadratic Roots
- What section is listed as 2.7?ComputerScienceOne · Quadratic Roots