Bifalgorithm post · Computer science one · Error Handling By Design

How can a quadratic roots function return error codes?

How can a quadratic roots function return error codes? (Computer science one · Error Handling By Design) — "As an example, let’s revisit the quadratic roots ex…

Ideas in this flowchart

  • La función quadraticRoots devuelve las raíces mediante parámetros de referencia y comunica los errores mediante un código entero.
  • Las dos raíces se devuelven mediante variables pasadas por referencia, dejando libre el valor de retorno.
  • El valor de retorno se utiliza ahora para indicar el resultado de las comprobaciones de error.
  • Si no se detecta ningún error, la función calcula y asigna las dos raíces.
  • La función que invoca quadraticRoots() puede comprobar el código devuelto para identificar el resultado.
  • Si a es igual a cero, existe una división por cero y se devuelve el código 1.
  • Si b² − 4ac es menor que cero, existen raíces complejas y se devuelve el código 2.
  • Si root1 o root2 es NULL, existe un error de puntero NULL y se devuelve el código 3.
  • Si no se encuentra ningún error, se devuelve el código 0.
  • La función calcula el discriminante y asigna las raíces a root1 y root2.
Feed/

How can a quadratic roots function return error codes?

No cover

Channel

Computer science one

1 page

"As an example, let’s revisit the quadratic roots example in Section 18.3.2. By returning the two output values via pass by reference variables, we freed up the return value. We can now modify our function to return an integer indicating an error code instead. Previously we had identified several different types of errors: division by zero (if a = 0), complex roots (if b 2 − 4 ac < 0) and a NULL pointer error if the variables passed by reference were NULL. We can now modify our function to check for these errors and return an appropriate error code. We return zero in the event that no error was encountered.\n\nint quadraticRoots(double a, double b, double c,\n\ndouble *root1, double *root2) {\n\nif(a == 0) {\n\nreturn 1;\n\n} else if( b*b - 4*a*c < 0 ) {\n\nreturn 2;\n\n} else if(root1 == NULL || root2 == NULL) {\n\nreturn 3;\n\n}\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 0;\n\n}\n\nNow when a function invokes our quadraticRoots() it can check to see what kind of"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.