Selected Reading

C++ cmath fmod() Function



The C++ cmath std::fmod() function is used to find the remainder of a division operation involving floating-point numbers. It divides one floating-point number by another and returns the remainder as a floating-point value, similar to how the modulo operator % works for integer numbers.

This is useful for applications like geometric calculations or cyclic behaviour where wrapping values within a certain range is necessary (e.g., angles in trigonometry).

Syntax

Following is the syntax for C++ cmath fmod() function.

double fmod(double x, double y);
or
float fmod(float x, float y);
or
long double fmod(long double x, long double y);

Parameters

  • x - The value of the quotient numerator.

  • y - The value of the quotient denominator.

Return Value

The function returns the remainder of dividing x by y as a floating-point value. The result has the same sign as x.

Time Complexity

The time complexity of this function is constant, i.e.,O(1).

Example 1

In the following example, we will use the fmod() function to perform a simple floating-point modulo operation.

#include <iostream>
#include <cmath>
int main() {
   double result = std::fmod(5.3, 2.0);
   std::cout << "fmod(5.3, 2.0) = " << result << std::endl;
   return 0;
}

Output

Output of the above code is as follows

fmod(5.3, 2.0) = 1.3

Example 2

This example demonstrates how fmod() works with negative values, calculating the remainder of given values while maintaining the sign of the dividend.

#include <iostream>
#include <cmath>
int main() {
   double x = -5.3;
   double y = 2.0;
   double result = fmod(x, y);
   std::cout << "fmod(-5.3, 2.0) = " << result << std::endl;
   return 0;
}

Output

Following is the output of the above code

fmod(-5.3, 2.0) = -1.3

Example 3

The following example demonstrates how the fmod() function handles decimal values for both the numerator and denominator.

#include <iostream>
#include <cmath>
int main() {
   double result = std::fmod(7.75, 2.5);
   std::cout << "fmod(7.75, 2.5) = " << result << std::endl;
   return 0;
}

Output

If we run the above code it will generate the following output

fmod(7.75, 2.5) = 0.25
cpp_cmath.htm
Advertisements