Error C# System.Indexoutofrangeexception

Asked

Viewed 38 times

1

Good with a doubt in this code , he in line 14 of me an error as you can see in the photo ...

Solutions ??

Thank youErro Code:

using System;
public class Exercise052
{
    public static void Main()
    {
        Console.Write("Cuantos datos reservo: ");
        int repeticiones = Convert.ToInt32(Console.ReadLine());
        float numero;
        float[] listaNumeros = new float[repeticiones];

        for (int i = 1; i <= repeticiones; i++)
        {
            Console.Write("Dime numero {0} para guardar en la lista: ", i);
            listaNumeros[i] = Convert.ToSingle(Console.ReadLine());
        }

        Console.Write("Que numero comprueba en la lista? ");
        numero = Convert.ToSingle(Console.ReadLine());

        while (Console.ReadLine() != "end")
        {
            for (int i = 1; i <= repeticiones; i++)
            {
                if (listaNumeros[i] == numero)
                    Console.WriteLine("El número {0} existe en la lista", numero);
            }
        }
    }
}
  • What is the error? Write the question. Do not use images.

  • The error that appears is " System.Indexoutofrangeexception: 'Index was Outside the Bounds of the array.'"

1 answer

0


The mistake really isn’t in the Convert.ToSingle() yes in its loop of repetition. The indices of an array start at 0 and not at 1, so when you arrive at the last iteration will give the error System.IndexOutOfRangeException: Index was outside the bounds of the array., that is, the Indice was outside the limits of the vector.

If the vector has 5 positions for example, the first position is the 0 and the last one is 4.

To fix your algorithm, you must change your for for:

for (int i = 0; i < repeticiones; i++)
{

}
  • I changed the code and continues the same error . But thank you for the answer if you have another possible hypotse.

  • Error continues on the same line?

  • Yes, unfortunately

  • I tested the code in repl.it and it worked perfectly. This is the link: https://repl.it/@natanfernandes1/Wellmadeillfatedprofiles

  • 1

    You’re absolutely right, I was running the old program... I’m sorry and thank you for helping me.

Browser other questions tagged

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