fork download
  1. #include <iostream>
  2. #include <stdlib.h>
  3.  
  4. uint8_t array[] = { 0, 64, 128, 192, 255 };
  5.  
  6. uint8_t findClosestMatch( uint8_t val )
  7. {
  8. uint8_t closest = 0;
  9. for ( uint8_t i = 0; i < sizeof array / sizeof array[0]; i++ )
  10. {
  11. if ( abs( val - closest ) >= abs( val - array[i] ) )
  12. closest = array[i];
  13. }
  14. return closest;
  15. }
  16.  
  17. int main()
  18. {
  19. printf( "closest from 72 = %hhu\n", findClosestMatch( 72 ) );
  20. printf( "closest from 142 = %hhu\n", findClosestMatch( 142 ) );
  21. printf( "closest from 230 = %hhu\n", findClosestMatch( 230 ) );
  22. return 0;
  23. }
Success #stdin #stdout 0s 2740KB
stdin
Standard input is empty
stdout
closest from 72  = 64
closest from 142 = 128
closest from 230 = 255