Modulus of two float or double numbers

1

Given two floating point numbers, find remainder.

Examples:

Input : a = 36.5,
        b = 5.0
Output : 1.5

Input :  a = 9.7, 
         b = 2.3
Output : 0.5

A simple solution is to do repeated subtraction.

// CPP program to find modulo of floating 
// point numbers.
#include <bits/stdc++.h>
using namespace std;

double findMod(double a, double b)
{
    // Handling negative values
    if (a < 0)
        a = -a;
    if (b < 0)
        b = -b;

    // Finding mod by repeated subtraction
    double mod = a;
    while (mod >= b)
        mod = mod - b;

    // Sign of result typically depends
    // on sign of a.
    if (a < 0)
        return -mod;

    return mod;
}

// Driver Function
int main()
{
    double a = 9.7, b = 2.3;
    cout << findMod(a, b);
    return 0;
}

Output :

0.5

We can use the inbuilt fmod function to find the modulus of two floating-point numbers.

// CPP program to find modulo of floating 
// point numbers using library function.
#include <bits/stdc++.h>
using namespace std;

// Driver Function
int main()
{
    double a = 9.7, b = 2.3;
    cout << fmod(a, b);
    return 0;
}

Output:

0.5

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 2 vote(s)