English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and examples of remainder() function

C++ Library Function <cmath>

C ++in which, the restder() function calculates the numerator/the floating-point remainder of the denominator (rounded to the nearest value).

remainder(x, y) = x - rquote * y

where, rquote is x/y's result, rounded to the nearest integer value (in half cases rounded to the nearest even number).

restder() prototype [from C ++ 11Standard]

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

restder() function accepts two parameters and returns a value of type double, float, or long double.

This function is in<cmath>are defined in the header file.

restder() parameters

  • x -the value of the numerator.

  • y -the value of the denominator.

restder() return value

restder() function returns x/y's floating-point remainder (rounded to the nearest value).

If the denominator y is zero, remainder() returns NaN (Not a Number).

Example1:How remainder() works in C ++How does remainder() work 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 " << x << ""/" << y << " = " << result << endl;
    x = -17.50, y =2.0;
    result = remainder(x, y);
    cout << "Remainder " << x << ""/" << y << " = " << result << endl;
    
    y = 0;
    result = remainder(x, y);
    cout << "Remainder " << x << ""/" << y << " = " << result << endl;
    
    return 0;
}

When the program is run, the output is:

Remainder 7.5/2.1 = -0.9
Remainder -17.5/2 = 0.5
Remainder -17.5/0 = -nan

Example2:remainder() function for different types of parameters

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int x = 5;
    double y = 2.13, result;
    
    result = remainder(x, y);
    cout << "Remainder " << x << ""/" << y << " = " << result << endl;
    return 0;
}

When the program is run, the output is:

Remainder  5/2.13 = 0.74

 C++ Library Function <cmath>