C#程序,生成20个随机数并在数组中搜索一个数字(续)

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

我正在重新发布并编辑它,因为我不知何故看不到旧的答案。老问题:我想制作一个生成20个随机数并在数组中搜索一个数字的程序。如果在输入中键入了20个随机数之一,则输出应显示“它在这里”。如果该数字不在ReadLine中,则应该说“是的”。我想知道如何制作所有20个随机数以便进行搜索。现在的代码只能搜索右边的数字。即使输入是20个随机数之一(右侧的数字除外),它也会说“不,它不在这里。”

NEW:我想通过2个for循环,一个用于创建数组和1个用于搜索数字的方法来完成这项工作。我已经对该程序进行了编辑,使其具有2个for循环,但输出效果很奇怪,如图所示。请通过编辑此代码以完成工作来帮助我,但仍然有2个for循环用于创建数组和1个用于搜索数字。Output1 Output2

 public static void Main(string[] args)
{

  Random random = new Random();
  int[] myIntArray = new int[100];


   for (int i=0; i <20; i++)
   {
     int x = random.Next(100);
     myIntArray[i] = x;
     Console.Write(myIntArray[i] + " ");
   } 
    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==myIntArray[i]) 
       {
          Console.WriteLine("Yes it is there.");

       }
      else
          Console.WriteLine("No it is not here.");

       }



    Console.ReadKey();
}
c# arrays for-loop search int
1个回答
0
投票
   if (z==myIntArray[i]) 
   {
      Console.WriteLine("Yes it is there.");

   }
   else
      Console.WriteLine("No it is not here.");  <- The problem is here

   }

在每个数字上,如果不匹配,则打印'No'。您应该使用定义的isValueFound变量,可以执行以下操作:

  1. 不在循环中打印任何内容
  2. [如果有匹配项,则将isValueFound发送为true,并中断循环
  3. 在第二个循环之外,检查isValueFound以确定是找到还是找不到。

此外,您也有很好的机会学习二进制搜索。编码愉快!

© www.soinside.com 2019 - 2024. All rights reserved.