Mesaje de eroare
Funcțiile tale C++ pot conține apeluri la funcția stop() pentru a genera excepții. Am definit parțial o funcție add_positive_numbers() pentru tine. Completează această funcție pentru a genera excepții.
Acest exercițiu face parte din cursul
Optimizarea codului R cu Rcpp
Instrucțiuni pentru exercițiu
- Dacă
xeste negativ, generează o excepție cu mesajul: "x is negative". - Dacă
yeste negativ, generează o excepție cu mesajul: "y is negative".
Exercițiu interactiv practic
Încearcă acest exercițiu completând acest cod de exemplu.
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)