if and if/else
Just like in R, you can use the if
and else
keywords for branching. The syntax is the same as in R.
if(condition) {
// Code to run if the condition is TRUE
} else {
// Code to run otherwise
}
Here you'll use if
and else
to complete the definition of an absolute()
function to calculate the absolute value of a floating point number. (This mimics the C++ function fabs()
.)
Este ejercicio forma parte del curso
Optimizing R Code with Rcpp
Instrucciones del ejercicio
- Test if x is greater than zero.
- If the condition holds, return
x
. - Add the keyword for what to do otherwise.
- If the condition doesn't hold, return negative
x
.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
#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)
*/