# [HELP] find closes number from array??

• 11-25-2012
Fromar123
[HELP] find closes number from array??
Hi,
well i have a userinput for an integer. And i have to get sqrt of that number and find the closes number from array... and i dont rly know how to do that... can anyone help?

heres the part for my input:
Code:

int poljubnostevilo;
cin >> poljubnostevilo;
cout <<endl;
int koren = sqrt (poljubnostevilo);
cout << koren << endl;

and here's the function i use to fill in the array with prime numbers,.. etc...so this function also has to return the closest number from the array to the sqrt of the inputed integer...

Code:

int funkcijatri(int x, int n){

n = 4;
int praarray[x];
int a=0;
int sum;
while(a<x){
n++;
if(IsPrime(n) && (n>=a)){
praarray[a] = n;
cout << praarray[a] << ", ";
sum+= praarray[a];
a++;

}//konec if

}//konec while

return sum/x;

}

Hope anyone can help me :)
• 11-25-2012
GReaper
An easy way ( or the only way? ) is to save a variable with the subtraction between userinput and each element of the array as you iterate through it. If the subtraction of userinput with each next element ( the absolute value, mind you ) is lower than the saved one, replace the old save with this one and also save the current index. When your iteration of the loop is over, you'll have the index of the closest value to userinput.
• 11-25-2012
Fromar123
ok, i know this will sound that im lazy or something, but can you post a sample of the code to implement please?, im kinda new to c++ and im not sure if i know how do that what you wrote... so any implementation samples? -would be really great :)