C++ fmod()

The fmod() function in C++ computes the floating point remainder of numerator/denominator (rounded towards zero).

fmod (x, y) = x - tquote * y

where tquote is truncated i.e. (rounded towards zero) result of x/y.


fmod() prototype [As of C++ 11 standard]

double fmod(double x, double y);
float fmod(float x, float y);
long double fmod(long double x, long double y);
double fmod(Type1 x, Type2 y); // Additional overloads for other combinations of arithmetic types

The fmod() function takes a two arguments and returns a value of type double, float or long double type. This function is defined in <cmath> header file.


fmod() Parameters

  • x: The value of numerator.
  • y: The value of denominator.

fmod() Return value

The fmod() function returns the floating point remainder of x/y. If the denominator y is zero, fmod() returns NaN (Not a Number).


Example 1: How fmod() works in C++?

#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;
}

When you run the program, the output will be:

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

Example 2: fmod() function for arguments of different types

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double x = 12.19, result;
    int y = -3;
    
    result = fmod(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;
    
    y = 0;
    result = fmod(x, y);
    cout << "Remainder of " << x << "/" << y << " = " << result << endl;

    return 0;
}

When you run the program, the output will be:

Remainder of 12.19/-3 = 0.19
Remainder of 12.19/0 = -nan

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges