0

I am supposed write a function that is passed two parameters: a one-dimensional array of int values, and an integer value. The function finds the value in the array that is closest in value to the second parameter. My code works but not when I enter numbers 1-5 my output is 0. When I enter numbers above 5 then I start getting accurate results. I am not too sure why this is happening but here is my code so far:

#include <iostream>
#include <cmath>
using namespace std;

const int MAX = 5;

int searchNearest(int anArray[],int key)
{
int value = abs(key - anArray[0]);
int num = 0;

for(int x = 0;x < MAX; x++)
{
    if(value > abs(key - anArray[x]))
    {
        value = abs(key - anArray[x]);
        num = anArray[x];
    }
}

return num;

}

int main()
{
int A[MAX] = {3,7,12,8,10};

int search;

int nearest;

cout << "Enter a number to search: ";

cin >> search;

nearest = searchNearest(A,search);

cout << "The nearest number is: " << nearest << endl;

system("pause");
return 0;

}

1 Answer 1

5

In your original code, numbers 1-5 are closest to the first element of the array. Because of this, the code in the if statement is never executed, and when you return num, you return its initial value, which happens to be 0. To fix this, just initialize num differently:

int num = anArray[0];  // <-- used to be 0
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh I knew I was overlooking something. Thanks for the help!
@Nick This is something that's pretty easy to diagnose with a debugger (or using printf or cout statements). It's also far less frustrating than staring at the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.