C# Array number next

Asked

Viewed 141 times

0

I’m in need of help I don’t know but where to turn. The problem and the following we have an Array of type Double.inserir a descrição da imagem aqui

We have a variable x = 91.30 in the Array (a) the nearest value is 91.39. I wanted to know how to get the variable y to receive the value of the index 91.39 which is closest to x. in case 91.30

  • 1

    It would be very interesting if you put the code in the post so we can do the proper tests.

1 answer

1


You can use Linq to get this number, and even briefly the index in the Array where it is.

Don’t forget to import the library System.Linq at the beginning of the code.

double[] arr = new double[] { 1.5, 1.7, 1.88, 2.0, 2.6, 3.0 };

double numeroBase = 1.65;
double numeroDaArray = arr.Aggregate((x,y) => Math.Abs(x - numeroBase) < Math.Abs(y - numeroBase) ? x : y);
int indice = Array.IndexOf(arr, numeroDaArray);

Console.WriteLine("Número {0} no índice {1} é o mais próximo de {2}.", numeroDaArray, indice, numeroBase);

See working on .NET Fiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.