fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. bool neighbours(double a, double b)
  5. {
  6. unsigned long long x;
  7. unsigned long long y;
  8. // not portable, yadda yadda yadda
  9. memcpy(&x, &a, 8);
  10. memcpy(&y, &b, 8);
  11. printf("distance: %llu\n", x - y);
  12. // no more than 1 apart?
  13. return x - y + 1 <= 2;
  14. }
  15.  
  16. const char * notstr[] = {"not ", ""};
  17.  
  18. void test(double a, double b)
  19. {
  20. printf("%.17f and\n%.17f are %sneighbours.\n\n", a, b, notstr[neighbours(a, b)]);
  21. }
  22.  
  23. const unsigned long long EVENS = 9007199254740992;
  24.  
  25. int main()
  26. {
  27. test(0.1 + 0.2, 0.3);
  28. test(0.5, 0.49999999999);
  29.  
  30. test(EVENS + 1, EVENS);
  31. test(EVENS + 2, EVENS);
  32. test(EVENS + 3, EVENS);
  33. test(EVENS + 4, EVENS);
  34. test(EVENS + 5, EVENS);
  35. }
  36.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
distance: 1
0.30000000000000004 and
0.29999999999999999 are neighbours.

distance: 180144
0.50000000000000000 and
0.49999999999000000 are not neighbours.

distance: 0
9007199254740992.00000000000000000 and
9007199254740992.00000000000000000 are neighbours.

distance: 1
9007199254740994.00000000000000000 and
9007199254740992.00000000000000000 are neighbours.

distance: 2
9007199254740996.00000000000000000 and
9007199254740992.00000000000000000 are not neighbours.

distance: 2
9007199254740996.00000000000000000 and
9007199254740992.00000000000000000 are not neighbours.

distance: 2
9007199254740996.00000000000000000 and
9007199254740992.00000000000000000 are not neighbours.