शुरू करेंमुफ़्त में शुरू करें

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().)

यह अभ्यास पाठ्यक्रम का हिस्सा है

Optimizing R Code with Rcpp

पाठ्यक्रम देखें

अभ्यास निर्देश

  • 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.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

#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)
*/
कोड संपादित करें और चलाएँ