简体   繁体   English

获取数组中数字的匹配索引

[英]Get matching index for a number in array

I'm new to programming and I've got confused on how to display the index number of a value in an array.我是编程新手,我对如何显示数组中值的索引号感到困惑。 I want to be able to type a random number and if the number I have entered is in the array, then it should tell me what the position (index) of the number is within the array.我希望能够键入一个随机数,如果我输入的数字在数组中,那么它应该告诉我该数字的 position(索引)在数组中是什么。

For example if I enter the number 6, and 6 is in my array and it's index is 4, then the output should be "That number exists, it is positioned at 4 in the array".例如,如果我输入数字 6,并且 6 在我的数组中并且它的索引是 4,那么 output 应该是“该数字存在,它位于数组中的 4”。 I've tried to do this but my code is the reverse of this, for example if I type in 6, then it looks for index 6 and outputs the number corresponding to index 6.我试过这样做,但我的代码与此相反,例如,如果我输入 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();


    }
}
}

You can use Array.IndexOf (gives you the index of given value in Array) instead of a[b] like this:您可以使用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");
}

You need to use Array.IndexOf() like below:您需要使用 Array.IndexOf() 如下所示:

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

在此处输入图像描述

Array.IndexOf returns -1 if the item dont exists in the array如果该项目不存在于数组中,则 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM