Bifalgorithm post · Computer science one · Quadratic Roots

How can pass-by-reference parameters return both roots of a quadratic equation?

How can pass-by-reference parameters return both roots of a quadratic equation? (Computer science one · Quadratic Roots) — "Another advantage of passing variab…

Ideas in this flowchart

  • El paso de variables por referencia permite comunicar varios valores con una sola llamada a función.
  • Una función puede manipular los contenidos de varios parámetros pasados por referencia.
  • Una función solo puede devolver como máximo un valor de forma estricta.
  • Los parámetros modificados comunican varios valores, aunque técnicamente no los devuelvan.
  • 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.
  • Sin parámetros por referencia, sería necesario escribir una función para cada raíz.
  • Una sola función puede recibir a, b y c por valor, además de root1 y root2 por referencia.
  • El código calcula el discriminante y coloca cada raíz en una variable pasada por referencia.
  • El uso de referencias evita la necesidad de definir varias funciones.
Feed/

How can pass-by-reference parameters return both roots of a quadratic equation?

No cover

Channel

Computer science one

1 page

"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, ax^2 + bx + c = 0, using the quadratic formula, (-b ± √(b^2 - 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 and place each one in two pass-by-reference variables.\n\nvoid quadraticRoots(double a, double b, double c,\n\ndouble *root1, double *root2) {\n\ndouble 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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.