Math Modf Function - C++ Programming Tutorial
C++ Course / Math Functions / Math Modf Function

Math Modf Function

BLUF: Mastering Math Modf Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Math Modf Function

C++ is renowned for its efficiency. Learn how Math Modf Function enables low-level control and high-performance computing in the tutorial below.

C++ Math modf

This function is utilized to separate a number into its integer and decimal components.

For example :

Example

2.16 = 2 + 16

Syntax

Suppose a value is denoted as 'x' and 'ptr' represents a pointer to an integer.

Example

float modf(float x, float* ptr);
double modf(double x, double* ptr);
long double modf(long double x, long double* ptr);
double modf(integral x, double* ptr);

Parameter

x : The value that needs to be divided into two components, specifically the fractional and integral parts.

The ptr variable refers to a memory location that holds the integer component of the value x.

Return value

It returns the integral part of x.

Example 1

Let's see a simple example

Example

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
 float x=18.26;
 double ptr;
 float i=modf(x,&ptr);
 std::cout << "Value of x is : " <<x <<std::endl;
 cout<<"integral part of x is :"<<ptr<<'\n' ;
 cout<<"fractional part of x is :"<<i;
 return 0;
}

Output:

Output

Value of x is : 18.26
integral part of x is :18
fractional part of x is :0.26

In this instance, the modf function separates a number into its integral and fractional components. The fractional segment is 0.26, while the integral portion is 18.

Example 2

Let's examine a basic scenario where the value of x is below zero.

Example

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    float x= -78.34;
    double ptr;
    float n=modf(x,&ptr);
    std::cout << "Value of x is : " <<x <<std::endl;
    cout<<"integral part of x is :"<<ptr<<'\n' ;
    cout<<"fractional part of x is :"<<n;
    return 0;
}

Output:

Output

Value of x is : -78.34
integral part of x is :-78
fractional part of x is :-0.339996

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience