Compare double base on precision : double « Data Types « C++ Tutorial






#include <iostream>
#include <cmath>

using namespace std;

bool doubleEquals(double left, double right, double epsilon) {
  return (fabs(left - right) < epsilon);
}

bool doubleLess(double left, double right, double epsilon, bool orequal = false) {
  if (fabs(left - right) < epsilon) {
    return (orequal);
  }
  return (left < right);
}

bool doubleGreater(double left, double right, double epsilon, bool orequal = false) {
  if (fabs(left - right) < epsilon) {
    return (orequal);
  }
  return (left > right);
}

int main( ) {
  double first = 0.33333333;
  double second = 1.0 / 3.0;

  cout << first << endl;
  cout << second << endl;

  cout << boolalpha << (first == second) << endl;
  cout << doubleEquals(first, second, .0001) << endl;
  cout << doubleLess(first, second, .0001) << endl;
  cout << doubleGreater(first, second, .0001) << endl;
  cout << doubleLess(first, second, .0001, true) << endl;
  cout << doubleGreater(first, second, .0001, true) << endl;
}
0.333333
0.333333
false
true
false
false
true
true








2.7.double
2.7.1.Convert feet to meters using doubles
2.7.2.Differences between int and double during 'divide'
2.7.3.Use the Pythagorean theorem to find find the length of the hypotenuse
2.7.4.Calculation by double variables
2.7.5.Compute the regular payments for a loan.
2.7.6.Show square roots of 1 to 99
2.7.7.how many rolls of wallpaper are required for a room with double type variables
2.7.8.Calculate the future value
2.7.9.Show decimal point field when displaying double and set filler
2.7.10.Do while loop: double value and fabs()
2.7.11.Compare double in if statement
2.7.12.Calcluate Exponents of a double value
2.7.13.Compare double base on precision
2.7.14.Use double value as the while loop counter
2.7.15.Check the value of a double read from keyboard