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

C++ frexp() function usage and example

C++ Library Function <cmath>

C ++The frexp(x, exp) function in the returns the mantissa and exponent of a floating-point number.

The binary significant bits are a floating-point number, whose absolute value (mantissa) is in the interval [0.5,1]. The integer exponent is2.

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

Mathematically

x = Binary significand * 2exponent

where the exponent is stored at the location pointed to by exp, and the binary significant bits are the value returned by frexp().

frexp() prototype [from C ++ 11Standard start]

double frexp(double x, int* exp);
float frexp(float x, int* exp);
long double frexp(long double x, int* exp);
double frexp(T x, int* exp); //for integer

frexp() function has two parameters and returns a binary significant value of double, float, or long double type.

frexp() parameters

  • x -the value to be decomposed.

  • exp -a pointer to an integer to store the exponent value.

frexp() return value

frexp() function returns the mantissa, whose absolute value is in the range [0.5,1]. If x is zero, both the significand and the exponent are zero.

frexp() return value
Parameter (x)Binary significant bitsExponent
000
x >= 1PositivePositive
x <= -1NegativePositive
-1 <x < 0NegativeNegative
0 < x <1PositiveNegative

Example1: frexp() function in C ++How does it work?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double x = 6.81, significand;
	int *exp;
	significand = frexp(x, exp);
	cout << x << " = " << significand << "" * 2^" << *exp << endl;
	return 0;
}

When the program is run, the output is:

6.81 = 0.85125 * 2^3

Example2: frexp() function with integer type

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double significand;
	int *exp, x = 25;
	significand = frexp(x, exp);
	cout << x << " = " << significand << "" * 2^" << *exp << endl;
	return 0;
}

When the program is run, the output is:

25 = 0.78125 * 2^5

  C++ Library Function <cmath>