fmod()

garanews's avatar
Published Oct 20, 2022Updated Dec 21, 2022
Contribute to Docs

The fmod() function returns the floating-point remainder of the division of two values (rounded towards zero). It is the extension of the modulo operation to floating-point numbers.

Syntax

fmod(numerator, denominator)

The quotient of the numerator divided by the denominator is rounded towards zero through truncation. The return type is a double, float, long double, or a combination of these types.

If the denominator is equal to zero, then either 0, NaN, or a domain error is returned. If a range error occurs, then the correct result is rounded and returned.

Note: The <cmath> header provides additional overloads for other combinations of arithmetic types (double, float, or long double). Overloaded functions cast the arguments to a double type before the calculation. If one of the arguments is a long double type, then both arguments are cast as long double types.

Example

The following example uses fmod() to return the floating-point remainder of x/y as a double type:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x = 7.5, y = 2.1;
double result = fmod(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
x = -17.50, y = 2.0;
result = fmod(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
return 0;
}

This will return the following output:

Remainder of 7.5/2.1 = 1.2
Remainder of -17.5/2 = -1.5

Codebyte Example

The following example is runnable and returns the floating-point remainder:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy