【问题标题】:C# Program that generates 20 random numbers and search the array for a number (Continued)生成 20 个随机数并在数组中搜索数字的 C# 程序(续)
【发布时间】:2020-09-01 05:54:15
【问题描述】:

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

新:我想通过 2 个用于创建数组的循环和 1 个用于搜索数字的循环来完成这项工作。我已将此程序编辑为具有 2 个 for 循环,但正如您在图片中看到的那样,输出很奇怪。请帮助我编辑此代码以完成工作,但仍然有 2 个 for 循环,一个用于创建数组,1 个用于搜索数字。

 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();
}

【问题讨论】:

  • Console.WriteLine("No it is not here."); 应该在循环之外。只有在您检查了所有号码并且没有找到号码后才打印。你有 isValueFound 变量。使用它。
  • 使用调试器单步执行最后一个for循环,你会看到发生了什么
  • 也考虑使用哈希集,这样你就不会有任何重复。 hashset 还会为您提供一个 contains 方法来检查该数字是否存在于集合中

标签: c# arrays for-loop search int


【解决方案1】:
   if (z==myIntArray[i]) 
   {
      Console.WriteLine("Yes it is there.");

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

   }

对于每个数字,如果不匹配,则打印“否”。您应该使用您定义的isValueFound 变量,您可以执行以下操作:

  1. 不要在循环中打印任何内容
  2. 当有匹配时发送isValueFound 为真,并打破循环
  3. 在第二个循环之外,检查isValueFound 以确定它是找到还是未找到。

此外,您还有一个学习二分搜索的好机会。编码愉快!

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多