C++ Standard Library C++ STL Library

C++ <cmath> - remainder() Function



The C++ <cmath> remainder() function returns the floating-point remainder of x/y (rounded to nearest integer). This can be mathematically expressed as below:

remainder = x - quotient * y

Where quotient is the result of x/y rounded towards nearest integer (with halfway cases rounded toward the even number).

Note: The fmod function is similar to the remainder function except the quotient is rounded towards zero instead of nearest integer. The remquo function is also very similar to the remainder function except it additionally stores the quotient internally used to determine the result.

Syntax

double remainder (double x, double y);
float remainder (float x, float y);
long double remainder (long double x, long double y);
double remainder (Type1 x, Type2 y);                    

Parameters

x Specify the value of numerator.
y Specify the value of denominator.

Return Value

Returns remainder of x/y. If y is zero, the function may either return zero or cause a domain error (depending on the library implementation).

Example:

In the example below, remainder() function is used to find out the remainder of a given division.

#include <iostream>
#include <cmath>
using namespace std;
 
int main (){
  cout<<remainder(23, 4)<<"\n";
  cout<<remainder(20, 4.9)<<"\n";
  cout<<remainder(20.5, 2.1)<<"\n"; 
  return 0;
}

The output of the above code will be:

-1
0.4
-0.5

❮ C++ <cmath> Library