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

C++ How to use the fmod() function and examples

C++ Library Function <cmath>

C ++where the fmod() function calculates the numerator/the floating-point remainder of the denominator (rounded).
fmod(x, y) = x - tquote * y

where tquote is truncated, that is, x / y's result (rounded).

fmod() prototype [from C ++ 11Standard Library]

double fmod(double x, double y);
float fmod(float x, float y);
long double fmod(long double x, long double y);
double fmod(Type1 x, Type2 y); //additional overloads for other arithmetic type combinations

The fmod() function accepts two parameters and returns a value of type double, float, or long double. This function is used for<cmath>are defined in the header file.

fmod() parameters

  • x: The value of the numerator.

  • y: The value of the denominator.

The fmod() return value

The fmod() function returns x / y's floating-point remainder. If the denominator y is zero, then fmod() returns NaN (Not a Number).

Example1: How does the fmod() function work in C ++how does it work in C?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    double x = 7.5, y = 2.1;
    double result = fmod(x, y);
    cout << "Remainder " << x << ""/" << y << " = " << result << endl;
    
    x = -17.50, y = 2.0;
    result = fmod(x, y);
    cout << "Remainder " << x << ""/" << y << " = " << result << endl;
    
    return 0;
}

When running the program, the output is:

Remainder 7.5/2.1 = 1.2
Remainder -17.5/2 = -1.5

Example2: The fmod() function is used for different types of parameters

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

When running the program, the output is:

Remainder 12.19/-3 = 0.19
Remainder 12.19/0 = -nan

  C++ Library Function <cmath>