生成20个随机数并在数组中搜索数字的程序

问题描述 投票:-1回答:2

我想制作一个生成20个随机数并在数组中搜索一个数字的程序。如果在输入中键入了20个随机数之一,则输出应显示“它在这里”。如果该数字不在ReadLine中,则应该说“是的”。我想知道如何制作所有20个随机数以便进行搜索。现在的代码只能搜索右边的数字。即使输入是20个随机数之一(右侧的数字除外),它也会说“不,它不在这里。”

图片是我当前的输出。正在显示20个数字。Output1 Output2

public static void Main(string[] args)
{
    Random random = new Random();
    int[] myIntArray = new int[100];

    for (int i = 1; i <= 20; i++)
    {
        int x = random.Next(100);

        myIntArray[i] = x;

        Console.Write(myIntArray[i] + " ");

        if (i == 20)
        {

            Console.Write("\nType a number to search for:");
            int z = Convert.ToInt32(Console.ReadLine());
            if (z == x)
            {
                Console.WriteLine("Yes it is there.");
            }
            else
            {
                Console.WriteLine("No it is not here.");
            }

        }
    }

    Console.ReadKey();
}
c# arrays search random int
2个回答
0
投票

您当前的代码检查20tyh项目(x)是否等于用户输入(z):

    if (i == 20) // 20th item only
    {    
        int z = Convert.ToInt32(Console.ReadLine());

        if (z == x) // if 20th item (x) equals to user input (z)
        {
            Console.WriteLine("Yes it is there.");
        }
        else
        {
            Console.WriteLine("No it is not here.");
        } 
    } 

尝试逐步解决问题:

public static void Main(string[] args)
{
    // Array...    
    int[] myIntArray = new int[20]; // We want 20 items, not 100, right? 

    // Of random items
    Random random = new Random(); 

    for (int i = 0; i < myIntArray.Length; ++i)
        myIntArray[i] = random.Next(100);

    // Debug: let's have a look at the array:     
    Console.WriteLine(string.Join(" ", myIntArray));

    // Time to ask user for a number
    Console.Write("Type a number to search for:");

    if (int.TryParse(Console.ReadLine(), out int number)) {
         // number is a valid integer number, let's scan myIntArray 
         bool found = false;

         foreach (int item in myIntArray)
             if (item == number) {
                 found = true;

                 break; 
             }   

        if (found) 
            Console.WriteLine("Yes it is there.");
        else
            Console.WriteLine("No it is not here.");                
    }
    else 
        Console.WriteLine("Not a valid integer");

    Console.ReadKey();
}

0
投票

因此,基本上,您应该创建一个循环,以一个带有一个数组的随机数初始化数组

for (int i = 1; i <= 20; i++)
    {
        int x = random.Next(100);

        myIntArray[i] = x;
    }

之后,您可以在另一个循环中的控制台中搜索键入的值

Console.Write("\nType a number to search for:");
bool isValueFound = false;
int z = Convert.ToInt32(Console.ReadLine());
for(int i=0; i<=20; i++){
    if (z == x)
            {
                Console.WriteLine("Yes it is there.");
            }
            else
            {
                Console.WriteLine("No it is not here.");
            }
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.