modf() – Function to separate integer and fraction part
Using the modf() function to separate the integer and fraction part of fractional value.
Learning Objectives
- Use of modf() function to separate the integer and fraction part of a fractional data such as float, double etc.
Source Code
|
|
Run Output
Code Understanding
double d=73.325;
This is the fraction we shall use as input for the separation of integer and fraction part.
double ipart;
The integer part is actually returned in a location (declared in this exampl with name ipart) passed to the function modf() as its second parameter.
cout<<“Fraction part of “<<d<<” = “<<modf(d,&ipart)<<endl;
Since the fraction part is returned output of the function we can call this function while writing the cout chain. In the modf(param1, param2)) function first parameter we pass the fractions to be divided and in the second part we pass the address of the location we decide to put the integer part. To pass the address of a variable location we prefix it with & (ampersand) character. So we pass it as &ipart in this example
cout<<“Integer part of “<<d<<” = “<<ipart<<endl;
Since the modf function has already run in the previous line the ipart variable is not expected to contain the integer part and thus we print it directly.
Notes
- For modern compilers it is advisable to use the cmath header file instead of math.h for full data compatibility.
- The return type of function is according to input values passed. If it is float it is float type return and so on.
Suggested Filename(s): modf.cpp
Created: 3-Jan-2018 19:55 | Updated: 3-Jan-2018 19:55|
