【问题标题】:Get matching index for a number in array获取数组中数字的匹配索引
【发布时间】:2019-10-07 19:54:51
【问题描述】:

我是编程新手,对如何在数组中显示值的索引号感到困惑。我希望能够键入一个随机数,如果我输入的数字在数组中,那么它应该告诉我该数字在数组中的位置(索引)是什么。

例如,如果我输入数字 6,并且 6 在我的数组中并且它的索引是 4,那么输出应该是“该数字存在,它在数组中位于 4”。我试过这样做,但我的代码与此相反,例如,如果我输入 6,它会查找索引 6 并输出与索引 6 对应的数字。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace searcharray
{ 

class Program
{
    static void Main(string[] args)
    {
        int n = 10;

        Random r = new Random();



        int[] a;

        a = new int[n + 1]; 

        for (int i = 1; i <= n; i++)
            a[i] = r.Next(1, 100); 


        for (int i = 1; i <= n; i++)
            Console.WriteLine(" a [" + i + "] = " + a[i]);



      Console.ReadLine();

        Console.WriteLine("Enter a number: ");
        int b = Convert.ToInt32(Console.ReadLine());


        if (a.Contains(b))

        {

            Console.WriteLine("That number exists and the position of the number is: " + a[b]);

        }
        else
        {
            Console.WriteLine("The number doesn't exist in the array");
        }


        Console.WriteLine();

        Console.ReadLine();


    }
}
}

【问题讨论】:

标签: c# arrays indexing


【解决方案1】:

您需要像下面这样使用 Array.IndexOf():

Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));

【讨论】:

    【解决方案2】:

    您可以像这样使用Array.IndexOf(为您提供数组中给定值的索引)而不是a[b]

    if (a.Contains(b))
    {
        Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
    }
    else
    {
        Console.WriteLine("The number doesn't exist in the array");
    }
    

    【讨论】:

      【解决方案3】:

      如果数组中不存在该项,Array.IndexOf 返回 -1

      var itemIndex = Array.IndexOf(a, b);
      if (itemIndex != -1)
      {
          Console.WriteLine("That number exists and the position of the number is: " + itemIndex);
      }
      else
      {
          Console.WriteLine("The number doesn't exist in the array");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-07
        • 1970-01-01
        • 1970-01-01
        • 2017-11-26
        • 2013-04-06
        相关资源
        最近更新 更多