Find closest number in array
int FindClosest(const int list[], int numElems, int value)
{
int diff = abs(list[0] - value), idx{ 0 };
for (int i = 0; i < numElems; i++)
{
if (abs(list[i] - value) < diff)
{
diff = abs(list[i] - value);
idx = i;
}
}
return idx;
}
int main()
{
int cSize = 5;
int iArr[cSize] = { 45,
38, 198, 36,781 };
int target = 40;
cout << "The closest number is: " << iArr[FindClosest(iArr, cSize, target)] << endl;
return 0;
}
Commenti
Posta un commento