fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4.  
  5. int dist(int a, int b)
  6. {
  7. return std::abs(b-a) ;
  8. }
  9.  
  10. unsigned getClosest( int* nums, unsigned nNums, int target )
  11. {
  12. unsigned indexOfClosest = 0 ;
  13.  
  14. unsigned index = 1 ;
  15. while ( index < nNums )
  16. {
  17. if ( dist(nums[index], target) < dist(nums[indexOfClosest], target) )
  18. indexOfClosest = index ;
  19.  
  20. ++index ;
  21. }
  22.  
  23. return indexOfClosest ;
  24. }
  25.  
  26. void displayClosest(int* nums, unsigned nNums, int target)
  27. {
  28. std::cout << "{ " ;
  29. for ( unsigned i=0; i<nNums; ++i )
  30. std::cout << nums[i] << ' ' ;
  31. std::cout << "}\n" ;
  32.  
  33. unsigned index = getClosest(nums, nNums, target) ;
  34. std::cout << "The closest number to " << target << " is " ;
  35. std::cout << nums[index] << " at index " << index << ".\n" ;
  36. }
  37.  
  38. int main()
  39. {
  40. std::srand(std::time(0)) ;
  41.  
  42. const unsigned array_size = 3 ;
  43. int array[array_size] = { std::rand() % 20, std::rand() % 20, std::rand() % 20 } ;
  44. for ( unsigned i=1; i<21; i+=2 )
  45. displayClosest(array, array_size, i) ;
  46. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
{ 6 3 11 }
The closest number to 1 is 3 at index 1.
{ 6 3 11 }
The closest number to 3 is 3 at index 1.
{ 6 3 11 }
The closest number to 5 is 6 at index 0.
{ 6 3 11 }
The closest number to 7 is 6 at index 0.
{ 6 3 11 }
The closest number to 9 is 11 at index 2.
{ 6 3 11 }
The closest number to 11 is 11 at index 2.
{ 6 3 11 }
The closest number to 13 is 11 at index 2.
{ 6 3 11 }
The closest number to 15 is 11 at index 2.
{ 6 3 11 }
The closest number to 17 is 11 at index 2.
{ 6 3 11 }
The closest number to 19 is 11 at index 2.