如何检查数组中是否包含数字并获取其索引?

时间:2015-04-17 14:24:16

标签: c#

如果我输入数字5,它在索引4处,它将在前3次给我not found,然后索引将与我输入的数字相同。

int[] A = { 3, 6, 4, 9, 10, 1, 2, 8 };
int myNumber;
int length = A.Length;
Console.WriteLine("enter your number");
myNumber = Convert.ToInt32(Console.ReadLine());

for (int i = 0; i < length; i++)
{
    if (myNumber == A[i])
    {
        Console.WriteLine("the numer" + myNumber + "is present in the array at the index" +" "+ A[i]);
    }
    else
    {
        Console.WriteLine("the number you entered are not found");
    }
    Console.ReadKey();
}

3 个答案:

答案 0 :(得分:5)

Array类有一个很好的IndexOf方法可以使用。它将返回您要查找的值的索引位置,或者如果找不到该值则返回-1。

int[] A = { 3, 6, 4, 9, 10, 1, 2, 8 };

Console.WriteLine("enter your number");
int myNumber = Convert.ToInt32(Console.ReadLine());

int indexLocation = Array.IndexOf(A, myNumber);
if (indexLocation > -1)
{
    Console.WriteLine("The number {0} was found at index location {1}", myNumber, indexLocation);
}
else
{
    Console.WriteLine("The number {0} was not found", myNumber);
}

答案 1 :(得分:1)

正确的计划:

int[] A = { 3, 6, 4, 9, 10, 1, 2, 8 };
int myNumber;
int length = A.Length;
Console.WriteLine("enter your number");
myNumber = Convert.ToInt32(Console.ReadLine());

// ADDED
bool found = false;

for (int i = 0; i < length; i++)
{
    if (myNumber == A[i])
    {
        found = true; // ADDED
        // On the far right of next row: Fixed A[i] -> i
        Console.WriteLine("the numer" + myNumber + "is present in the array at the index" + " " + i); 
        break;
    }
}

// ADDED
if (!found)
{
    Console.WriteLine("the number you entered are not found");
}

Console.ReadKey();

我希望/认为你可以在没有帮助的情况下看到/理解差异。

我将补充说,有第二种方法可以解决这个问题:

int[] A = { 3, 6, 4, 9, 10, 1, 2, 8 };
int myNumber;
int length = A.Length;
Console.WriteLine("enter your number");
myNumber = Convert.ToInt32(Console.ReadLine());

// MOVED OUTSIDE FOR
int i = 0;

for (; i < length; i++)
{
    if (myNumber == A[i])
    {
        // On the far right of next row: Fixed A[i] -> i
        Console.WriteLine("the numer" + myNumber + "is present in the array at the index" + " " + i);
        break;
    }
}

// ADDED
if (i == length)
{
    Console.WriteLine("the number you entered are not found");
}

Console.ReadKey();

查看区别:found不是必需的,我们只使用扩展了“范围”的i变量。

答案 2 :(得分:0)

您希望将代码更改为此类代码。你的第一个错误是打印A [i]而不是i,你的第二个错误就是在循环中打印未找到的消息。如果将它移到循环外,它将只打印一次,同样适用于Console.ReadKey()

 int[] A = { 3, 6, 4, 9, 10, 1, 2, 8 };
    int myNumber;
    int length = A.Length;
    Console.WriteLine("enter your number");
    myNumber = Convert.ToInt32(Console.ReadLine());

    bool isFound = false;
    for (int i = 0; i < length; i++)
    {
        if (myNumber == A[i])
        {

            Console.WriteLine("the numer" + myNumber + "is present in the array at the index" +" "+ i);

            isFound = true;
        }          
    }

   if (!isFound)
   {
      Console.WriteLine("the number you entered are not found");
   }

   Console.ReadKey();

}

}