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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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.