Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use modf() in C++

Sadia Zubair

The modf function in C++ is used to perform mathematical calculations. It splits the first argument provided into integer and fractional parts.

To use the modf function, the cmath header file needs to be included in the program:

#include <cmath>
Figure 1

Parameters

The modf function takes in two parameters:

  1. The value to be broken down into the integral and the fractional part.
  2. The pointer to an object of the same type as the first argument, where the integral part of the first argument is stored.

Return value

The return value of the modf function is the fractional part of the first argument passed to the function.

The modf function can have three types of return value:

  • float
  • double
  • long double

These types depend on the type of arguments the programmer gives to the functions.

Example

The code below shows how the modf function works in C++. The integral value will be stored in the memory address where &intPart points.

Initially, the intPart variable had a value zero stored. However, after the modf function is applied in line 11, the value is changed to 14:

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

int main ()
{
	double val = 14.86;
    double intPart = 0;
    double fractPart = 0;
	
	fractPart = modf(val, &intPart);
	cout << "The returned value of the modf function is " << fractPart << endl;
	cout << "The value of integral  stored is " << intPart << endl;

	return 0;
}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring