English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and example of modf() function

C++ Library Function <cmath>

C ++The modf() function in the library divides the number into integer and fractional parts.

As mentioned earlier, modf(x, intptr) decomposes the number into integer and fractional parts. Decomposes the floating-point value x into fractional and integer parts, each having the same sign as x. Returns the signed fractional part of x, and stores the integer part as a floating-point value at intptr.

This function is in<cmath>defined in the header file.

modf() prototype [from C ++ 11Standard beginning]

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 integer type

modf() parameters

modf() has two parameters:

  • x - The value is divided into two parts.

  • intpart - pointing to the object (type andxThe same object, this part is stored with the same sign asxThe same sign is stored in the integer part.

modf() return value

The modf() function returns the fractional part of the parameter it is passed.

Example1: How does modf() work?

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
	double x = 14.86, intPart, fractPart;
	
	cout << x << " = " << intPart << '"', + " << fractPart << endl;
	x = -31.201;
	
	cout << x << " = " << intPart << '"', + " << fractPart << endl;
	return 0;
}

When the program is executed, the output is:

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

Example2: modf() with integer value as the first parameter

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
	int x = 5;
	double intpart, fractpart;
	fractpart = modf(x, &intpart);
	cout << x << " = " << intpart << "\n" + " << fractpart << endl;
	return 0;
}

When the program is executed, the output is:

5 = 5 + 0

C++ Library Function <cmath>