C++ Math modf
This function is utilized to separate a number into its integer and decimal components.
For example :
2.16 = 2 + 16
Syntax
Suppose a value is denoted as 'x' and 'ptr' represents a pointer to an integer.
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
#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:
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.
#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:
Value of x is : -78.34
integral part of x is :-78
fractional part of x is :-0.339996