2

I'm having a problem with the fmod() function.

This code should be true, but somehow it's not. Any help?

if (fmod(1.9, 0.3) == 0.1) {  
    cout << "True." << endl;  
}
Mathew Block
  • 1,613
  • 1
  • 10
  • 9
ParkerR
  • 23
  • 4

1 Answers1

2

Floating point number aren't exact. One way you could do this is,

#include <limits>

if (fabs(fmod(1.9,0.3) - 0.1) <  std::numeric_limits<double>::epsilon()) {
    cout << "True." << endl;
}

However, this is a crude solution that isn't entirely correct. Do a few searches for how to compare doubles/floats on stackoverflow for some discussions on the issue.

PherricOxide
  • 15,493
  • 3
  • 28
  • 41