Komunikaty o błędach
Twoje funkcje C++ mogą zawierać wywołania funkcji stop(), które zgłaszają wyjątki. Częściowo zdefiniowaliśmy dla ciebie funkcję add_positive_numbers(). Uzupełnij tę funkcję, aby zgłaszała wyjątki.
To ćwiczenie jest częścią kursu
Optymalizacja kodu R za pomocą Rcpp
Instrukcje do ćwiczenia
- Jeśli
xjest ujemne, zgłoś wyjątek z komunikatem: "x is negative". - Jeśli
yjest ujemne, zgłoś wyjątek z komunikatem: "y is negative".
Interaktywne ćwiczenie praktyczne
Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.
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)