C++ modf()

The modf() function in C++ breaks a number into integral and fractional part.

As mentioned, modf() breaks a number to integral and fractional part. The fractional part is returned by the function and the integer part is stored in the address pointed by pointer passed to modf() as argument.

This function is defined in <cmath> header file.


modf() prototype [As of C++ 11 standard]

double modf (double x, double* intpart);
float modf (float x, float* intpart);
long double modf (long double x, long double* intpart);
double modf (T x, double* intpart);  // T is an integral type

modf() Parameters

The modf() takes two parameters:

  • x - Value to be broken into two parts.
  • intpart - Pointer to an object (of the same type as x) where the integral part is stored with the same sign as x.

modf() Return Value

The modf() function returns the fractional part of the argument passed to it.


Example 1: How modf() works?

#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
	double x = 14.86, intPart, fractPart;
	
	fractPart = modf(x, &intPart);
	cout << x << " = " << intPart << " + " << fractPart << endl;
	
	x = -31.201;
	fractPart = modf(x, &intPart);
	cout << x << " = " << intPart << " + " << fractPart << endl;

	return 0;
}

When you run the program, the output will be:

14.86 = 14 + 0.86
-31.201 = -31 + -0.201

Example 2: modf() With Integer Value as First Argument

#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
	int x = 5;
	double intpart, fractpart;
	fractpart = modf(x, &intpart);
	cout << x << " = " << intpart << " + " << fractpart << endl;
	
	return 0;
}

When you run the program, the output will be:

5 = 5 + 0