In this C++ tutorial, you will learn how to break a given number into integral and fractional part using modf() function of cmath, with syntax and examples.

C++ modf()

C++ modf() breaks given number (argument) into integral and fractional part.

Integral part is stored at the location given by the second argument to this function, and the fractional part is returned by the function.

Syntax

The syntax of C++ modf() is

modf(x, intpart)

where

ParameterDescription
xA value to be broken into parts.
intpartA pointer to an object where the integral part of the result is stored.

Returns

The return value depends on the type of value passed for parameter x.

The return value of modf(x) is

  • double if x is double or integral type.
  • float if x is float.
  • long double if x is long double.

The synopsis of modf() function is

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); // for integral type argument values

modf() is a function of cmath library. Include cmath library in the program, if using modf() function.

ADVERTISEMENT

Example

In this example, we

C++ Program

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

int main() {
    double x;
    cout << "Enter a number : ";
    cin >> x;
    
    double intpart;
    double fraction = modf(x, &intpart);
    cout << "Integral : " << intpart << endl;
    cout << "Fraction : " << fraction << endl;
}

Output

Enter a number : 3.14
Integral : 3
Fraction : 0.14
Program ended with exit code: 0
Enter a number : -2.896
Integral : -2
Fraction : -0.896
Program ended with exit code: 0
Enter a number : 0
Integral : 0
Fraction : 0
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ modf(), and how to use this function to get the integral and fractional parts of given number, with the help of examples.