Skip to content

Instantly share code, notes, and snippets.

@bruceoutdoors
Created November 17, 2014 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bruceoutdoors/5a9a85dc3154ef500ca2 to your computer and use it in GitHub Desktop.
Save bruceoutdoors/5a9a85dc3154ef500ca2 to your computer and use it in GitHub Desktop.
when using double, take note of its precision problem (float and double only store decimal estimates) if you find certain values does not match. A possible solution is to use a custom Round function.
#include <iostream>
#include <cmath>
using namespace std;
// rounds a double variable to nPlaces decimal places
double Round(double dbVal, int nPlaces /* = 0 */)
{
const double dbShift = pow(10.0, nPlaces);
return floor(dbVal * dbShift + 0.5) / dbShift;
}
int main()
{
double t = 0.1;
double f = 0.2;
t = t + f;
double q = 0.3;
cout << "t = " << t << endl;
cout << "q = " << q << endl;
/* uncomment to see round function at work */
// t = Round(t, 1);
if (t == q) {
cout << "t and q are equal!" << endl;
} else {
cout << "t and q are NOT equal." << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment