Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use the remainder() function in C++

Sadia Zubair

The remainder function returns the floating-point remainder, which is computed by dividing the numerator with the denominator.

In order to use the remainder function, the cmath header file needs to be included in the program:

#include <cmath>

Figure 1 below shows how the remainder function calculates the remainder. The rquote is found by dividing the numerator with the denominator and then rounding off to the nearest integer value.

Figure 1

Parameters

The function takes in two parameters:

  1. The value of the numerator
  2. The value of the denominator

Return value

The remainder function can have three types of return value:

  • float
  • double
  • long double

These types depend on the type of arguments the programmer gives to the functions.

If the value of the second argument is zero, the function returns NaN.

If any argument passed to the remainder function is long double, then the return type is long double. If not, the return type is double. If both arguments are of type float, the return type is also float.

Example

The code below shows how the remainder function functions in C++. Both the arguments are of the same type, which results in the returned value being the same as that of the argument types.

#include <iostream>
#include <cmath>
#include <typeinfo> 
using namespace std;

int main() {
  // both the arguments are of same type.
  double val1 = 7.5;
  double val2 = 2.1;
  cout << "The remainder of " << val1 << "/" << val2 << " is " << remainder(val1,val2) << endl;
  // the type of returned value is output d which means the returned value is of type double.
  cout << "The type of returned value is " << typeid( (remainder(val1,val2))).name() << endl;
  return 0;
}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring