ComenzarEmpieza gratis

Mensajes de error

Tus funciones en C++ pueden incluir llamadas a la función stop() para lanzar una excepción. Hemos definido parcialmente una función add_positive_numbers() para ti. Complétala para que lance excepciones.

Este ejercicio forma parte del curso

Optimizar código de R con Rcpp

Ver curso

Instrucciones del ejercicio

  • Si x es negativo, lanza una excepción con el mensaje: "x is negative".
  • Si y es negativo, lanza una excepción con el mensaje: "y is negative".

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

cppFunction('
  // adds x and y, but only if they are positive
  int add_positive_numbers(int x, int y) {
      // if x is negative, stop
      if(___) stop("x is negative") ;
    
      // if y is negative, stop
      if(___) ___("y is negative") ;
     
      return x + y ;
  }
')

# Call the function with positive numbers
add_positive_numbers(2, 3)

# Call the function with a negative number
add_positive_numbers(-2, 3)
Editar y ejecutar código