Find number from given list for which value of the function is closest to A | C ++ program to find number from given list for which value of the function is closest to A ; Function to find number from given list for which value of the function is closest to A ; Stores the final index ; Declaring a variable to store the minimum absolute difference ; Finding F ( n ) ; Updating the index of the answer if new absolute difference is less than tmp ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int leastValue ( int P , int A , int N , int a [ ] ) { int ans = -1 ; float tmp = ( float ) INFINITY ; for ( int i = 0 ; i < N ; i ++ ) { float t = P - a [ i ] * 0.006 ; if ( abs ( t - A ) < tmp ) { tmp = abs ( t - A ) ; ans = i ; } } return a [ ans ] ; } int main ( ) { int N = 2 , P = 12 , A = 2005 ; int a [ ] = { 1000 , 2000 } ; cout << leastValue ( P , A , N , a ) << endl ; }