fork(1) download
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. double n0 = 0.5;
  5. double n1 = -0.5;
  6.  
  7. //special number, should round to zero
  8. double n2 = 0.49999999999999994;
  9. double n3 = -0.49999999999999994;
  10.  
  11. int32_t round_naive( double n ) {
  12.  
  13. return n + 0.5;
  14. }
  15.  
  16. int32_t round_less_naive( double n ) {
  17.  
  18. return n > 0.0 ? n + 0.5 : n - 0.5;
  19. }
  20.  
  21. int32_t round_my_try( double n ){
  22.  
  23. int32_t n2 = (int32_t)( n * 2.0 ); // double it
  24. int bit = n2 & 0x1; // extract the half-bit
  25. bit = n2 >> 31 ? -bit : bit; // check sign
  26. return n2/2 + bit; // adjust
  27. }
  28.  
  29. void test( double n ) {
  30.  
  31. printf( "round_naive ( %.17f ) -> %d\n", n, round_naive( n ) );
  32. printf( "round_less_naive ( %.17f ) -> %d\n", n, round_less_naive( n ) );
  33. printf( "round_my_try ( %.17f ) -> %d\n\n", n, round_my_try( n ) );
  34. }
  35.  
  36. int main(void) {
  37.  
  38. test( n0 );
  39. test( n1 );
  40. test( n2 );
  41. test( n3 );
  42.  
  43. return 0;
  44. }
  45.  
  46.  
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
round_naive      ( 0.50000000000000000 ) -> 1
round_less_naive ( 0.50000000000000000 ) -> 1
round_my_try     ( 0.50000000000000000 ) -> 1

round_naive      ( -0.50000000000000000 ) -> 0
round_less_naive ( -0.50000000000000000 ) -> -1
round_my_try     ( -0.50000000000000000 ) -> -1

round_naive      ( 0.49999999999999994 ) -> 1
round_less_naive ( 0.49999999999999994 ) -> 1
round_my_try     ( 0.49999999999999994 ) -> 0

round_naive      ( -0.49999999999999994 ) -> 0
round_less_naive ( -0.49999999999999994 ) -> -1
round_my_try     ( -0.49999999999999994 ) -> 0