错误信息
您的 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)