Friday, 9 March 2012

The modf Function in C & C++

More functions from the  <math.h> or <cmath> header files. Today it’s about the modf function.

This function returns two values. To do that, one part is returned by way of assignment (e.g., R1 = fn). The second part is return by storing the value in the second argument. (e.g., R1 = f(a,R2). It accomplishes this by using pointers.

The modf function takes a floating point number, e.g., a.b, and breaks the two apart such that R1 = b and R2 = a. R2 is the fractional part. R1 is the integral part.

From C11 standard.

// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library.
#include <cstdio>

// C++ math library.
#include <cmath>

int main()
     // Header.
     printf("modf Function\n\n");
     printf("R1 = modf(a,R2) \n\n");

     double R1, R2;
     double a = 123.456;

     R1 = modf(a, &R2);
     printf("a = 123.456 R1 = %6.3f\tR2 = %3.f\n\n", R1, R2);

     // Keep console window open.

     // Return some value.
     return 0;
} // end main


No comments:

Post a Comment