How to implement fmod (floating-point remainder) in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>

using namespace std;

double get_fmod(double a, double b) { 
    double f_mod = a; 
    
    if (a < 0) 
        f_mod = -a; 

    if (b < 0) 
        b = -b; 
  
    while (f_mod >= b) 
        f_mod = f_mod - b; 
  
    if (a < 0) 
        return -f_mod; 
  
    return f_mod; 
} 
  
int main() 
{ 
    double a = 10.7, b = 3.3; 
    
    cout << get_fmod(a, b) << endl; 
    cout << fmod(a, b); 
    
    return 0; 
}


/*
run:

0.8
0.8

*/

 



answered Sep 24, 2019 by avibootz
...