- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find number from given list for which value of the function is closest to A in C++

Suppose we have a function F(n) such that F(n) = P – (0.006*n), where P is also given. Given a list of integers and a number A. The task is to find the number from given list, for which the value of the function is nearer to A. So if P = 12, and A = 5, then list will be {1000, 2000} So output will be 1000. So if P = 12 and A = 5, then for 1000, F(1000) = 12 – (0.006 * 1000) = 6 and for 2000, F(2000) = 12 – (0.006 * 2000) = 0, as the nearest value to 5 is the 6, so that is taken.

Iterate through each value in the list, and find F(n) for every value. Now compare the absolute difference of every value of F(n) and A and the value of n, for which the absolute difference is minimum, will be the answer.

## Example

#include<iostream> #include<cmath> using namespace std; int nearestValue(int P, int A, int N, int arr[]) { int ans = -1; float temp = (float)INFINITY; for (int i = 0; i < N; i++) { float term = P - arr[i] * 0.006; if (abs(term-A) < temp) { temp = abs(term - A); ans = i; } } return arr[ans]; } int main() { int P = 12, A = 5; int array[] = {1000, 2000, 1001}; int N = sizeof(array)/sizeof(array[0]); cout << "Nearest value is: " << nearestValue(P, A, N, array) << endl; }

## Output

Nearest value is: 1001

- Related Articles
- Find k closest elements to a given value in C++
- Find the closest index to given value in JavaScript
- Which MySQL function is used to find first non-NULL value from a list of values?
- Find the multiple of x which is closest to a^b in C++
- Find closest value for every element in array in C++
- Find closest greater value for every element in array in C++
- Find closest smaller value for every element in array in C++
- Find three closest elements from given three sorted arrays in C++
- Program to find list that shows closest distance of character c from that index in Python
- Find closest number in array in C++
- Count the number of intervals in which a given value lies in C++
- Find Itinerary from a given list of tickets in C++
- Find the closest and smaller tidy number in C++
- Finding closest pair sum of numbers to a given number in JavaScript
- Program to find value for which given array expression is maximized in Python

Advertisements