# Thread: choosing a number from a list of numbers

1. ## choosing a number from a list of numbers

Need help in trying to write a piece of code that rounds a users integer input to the closest set of predefined numbers.

e.g.

defined values 30, 31, 36, 37

user enters 35

therefore I need some code that will choose the value 36, since its the closest match to the defined values. The only way I could think is a load of if statements. I've been out of touch with C for a while would really appeciate some help.

Thanks

2. if else statements aren't death, and there are a few things you can do to make life easier. If the number is <= 30 or >= 37, that's pretty simple. But you can consign the rest to single else-ifs by saying something to the effect of

else if (n >= 31 && n <= 33)
{
printf("31");
}

else if (n >= 34 && n <= 36)
{
printf("36");
}

So you can just add the if and else if for 30 and 37, and you can get away with only 4 switches.

Hope this helps.

starX
www.axisoftime.com

3. can you be a bit more specific when using the array method, I mean I know the principles behind what I need to do, but I dont have the programming experience to do it.

I've defined a series of numbers in an array, what I need to do is compair a value the user has given and display the closest value in the array to the users.???

4. Salem pretty much told you how it's done, but here's a (possibly) working example:

Code:
```int array[5];

int num;

int current,
position = 0,
temp = 1000;

// fill array

// get num

for(i = 0; i < 5; i++)
{

current = num - array[i];

if(abs(current) < temp)
{
temp = abs(current);
position = i;
}
}

printf("Closest Match: %i \n\n", array[position]);```

5. Yeah, all it is is general math and comparing the outcome of subtracting and adding the results of the two closest choices.

--Garfield