Thông báo lỗi
Các hàm C++ của bạn có thể gọi hàm stop() để ném ngoại lệ. Chúng tôi đã định nghĩa sẵn một phần hàm add_positive_numbers() cho bạn. Hãy hoàn thiện hàm này để ném ngoại lệ.
Bài tập này là một phần của khóa học
Tối ưu hóa mã R với Rcpp
Hướng dẫn bài tập
- Nếu
xlà số âm, hãy ném một ngoại lệ với thông báo: "x is negative". - Nếu
ylà số âm, hãy ném một ngoại lệ với thông báo: "y is negative".
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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)