fork download
  1. #include <algorithm>
  2. #include <numeric>
  3. #include <iostream>
  4. #include <cmath>
  5.  
  6. int main()
  7. {
  8. float values[] = { 1, 2, 3, 4, 5 };
  9. const int numValues = sizeof(values) / sizeof(float);
  10.  
  11. // get the average
  12. float average = std::accumulate(values, values + numValues, 0.0F) / numValues;
  13.  
  14. // sort the values
  15. std::sort(values, values + numValues);
  16.  
  17. // find where the average would be inserted
  18. float *closest = std::upper_bound(values, values + numValues, average);
  19.  
  20. // assume closest is the value greater than average
  21. float *absClosest = closest;
  22.  
  23. // check number before the insertion point
  24. if (closest != values)
  25. {
  26. float *closest2 = closest - 1;
  27.  
  28. // get the difference in both numbers and average
  29. if (fabs(*closest2 - average) < fabs(*closest - average))
  30. absClosest = closest2;
  31. }
  32. std::cout << "The average is " << average << "\nThe closest to average is " << *absClosest;
  33. }
  34.  
Success #stdin #stdout 0s 4352KB
stdin
Standard input is empty
stdout
The average is 3
The closest to average is 3