Bifalgorithm post · Computer science one · Quadratic Roots

How can PHP pass variables by reference to return multiple quadratic roots?

How can PHP pass variables by reference to return multiple quadratic roots? (Computer science one · Quadratic Roots) — "40.2.2. Quadratic Roots Another advanta…

Ideas in this flowchart

  • Pasar variables por referencia permite comunicar múltiples valores en una sola llamada a función.
  • Una función está limitada a devolver como máximo un valor.
  • Varios parámetros por referencia permiten que la función modifique sus contenidos.
  • Así, la función comunica múltiples valores aunque no los devuelva estrictamente.
  • El cálculo de las raíces de una ecuación cuadrática ejemplifica esta ventaja.
  • La fórmula cuadrática produce dos raíces, una con el signo más y otra con el signo menos.
  • Una sola función puede recibir a, b y c por valor, y root1 y root2 por referencia.
  • La función calcula ambas raíces y las almacena en las variables de referencia.
  • Este enfoque evita escribir funciones separadas para cada raíz.
  • Existen entradas problemáticas, como raíces complejas o un coeficiente a igual a cero.
  • El manejo de estos errores se examina en el capítulo siguiente.
Feed/

How can PHP pass variables by reference to return multiple quadratic roots?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.