The remainder() function in C++ computes the floating point remainder of numerator/denominator (rounded to nearest).
remainder (x, y) = x - rquote * y
where rquote
is the result of x/y
, rounded towards the nearest integral value (with halfway cases rounded towards the even number).
remainder() prototype [As of C++ 11 standard]
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); // Additional overloads for other combinations of arithmetic types
The remainder() function takes two arguments and returns a value of type double, float or long double type.
This function is defined in <cmath> header file.
remainder() Parameters
- x - The value of numerator.
- y - The value of denominator.
remainder() Return value
The remainder() function returns the floating point remainder of x/y
(rounded to nearest).
If the denominator y is zero, remainder() returns NaN
(Not a Number).
Example 1: How remainder() works in C++?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = 7.5, y = 2.1;
double result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
x = -17.50, y=2.0;
result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
y=0;
result = remainder(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 = -0.9 Remainder of -17.5/2 = 0.5 Remainder of -17.5/0 = -nan
Example 2: remainder() function for arguments of different types
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int x = 5;
double y = 2.13, result;
result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
return 0;
}
When you run the program, the output will be:
Remainder of 5/2.13 = 0.74
Also Read: