You are using a version without Ads of this website. Please, consider donating:

### Need to find the number in an array closest to a value

So i need to find out which float value in an array holding 16 numbers is closest to another float value (all values are constantly changing). The range for all values is -180 to positive 180 (So a circle). I need to make this into a function so i can call it multiple times. Can anyone give me a hand? Ty very much in advance.
hrmm that sounds like a goo beginner challenge, i cant think of anything now i will get back to you and start working on it myself straight away im thinking of adding o.o1 to see if my chosen number is within <or> bounds and then trying o.oo1 then checking if it is in bounds, or the other way, subtracting 0.001 untill only one == comes up.

EDIT: so if there are 16 numbers i have to find the closest 2?
Last edited on
Haven't checked it.
 ``1234567891011121314151617181920212223242526272829303132333435363738`` ``````float findVal(float a, float * floatArray) { float valA = a; float dif = 0; float retVal = 0; //create our array //float* floatArray = new float[16]; //loop through array to check for values for(int i=0; i<16;i++) { if(i==0) { retVal = floatArray[i]; dif = (a-retVal); } if((floatArray[i]-a) < dif) { retVal = floatArray[i]; dif = (a-retVal); } } cout<<"The Closest Number is" << "\n" << retVal << "\n" << "With a difference of " << dif << "\n"; return dif; }//end function int _tmain(int argc, _TCHAR* argv[]) { float* myArray = new float[16]; //fill our array for(int i=0; i<16;i++) { myArray[i] = i; } float df = findVal(24,myArray); system("pause"); return 0;``````
Topic archived. No new replies allowed.