錯誤訊息
你的 C++ 函式可以呼叫 stop() 來丟出例外。我們已幫你部分定義了 add_positive_numbers() 函式。請完成此函式以在需要時丟出例外。
本練習屬於課程
用 Rcpp 最佳化 R 程式碼
練習說明
- 如果
x為負數,丟出訊息為:「x is negative」。 - 如果
y為負數,丟出訊息為:「y is negative」。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)