if 與 if/else
就像在 R 中一樣,你可以用關鍵字 if 和 else 來做分支。語法和 R 相同。
if(condition) {
// Code to run if the condition is TRUE
} else {
// Code to run otherwise
}
在這裡,你會用 if 和 else 來完成 absolute() 函式的定義,用於計算浮點數的絕對值。(這模仿了 C++ 的函式 fabs()。)
本練習屬於課程
用 Rcpp 最佳化 R 程式碼
練習說明
- 測試 x 是否大於 0。
- 若條件成立,回傳
x。 - 加上「否則」要執行的關鍵字。
- 若條件不成立,回傳
x的負值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
#include
using namespace Rcpp ;
// [[Rcpp::export]]
double absolute(double x) {
// Test for x greater than zero
___(___) {
// Return x
___;
// Otherwise
} ___ {
// Return negative x
___;
}
}
/*** R
absolute(pi)
absolute(-3)
*/