[英]Program that generates 20 random numbers and search the array for a number
[英]C# Program that generates 20 random numbers and search the array for a number (Continued)
我正在重新发布并编辑它,因为我不知何故看不到旧答案的答案。 老问题:我想制作一个生成 20 个随机数并在数组中搜索一个数字的程序。 如果在输入中输入了 20 个随机数之一,则 output 应该说“它在这里”。 如果数字不在 ReadLine 中,它应该说“是的,它在那里”。我想知道如何使所有 20 个随机数都能够搜索。 现在的代码只能搜索右边的数字。 即使输入是 20 个随机数之一,除了右边的那个,它也会说“不,它不在这里”。
新:我想通过 2 个用于创建数组的循环和 1 个用于搜索数字的循环来完成这项工作。 我已经将这个程序编辑为有 2 个 for 循环,但 output 很奇怪,正如您在图片上看到的那样。 请通过编辑此代码来帮助我完成工作,但仍然有 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();
}
if (z==myIntArray[i])
{
Console.WriteLine("Yes it is there.");
}
else
Console.WriteLine("No it is not here."); <- The problem is here
}
在每个数字上,如果不匹配,则打印“否”。 您应该使用您定义的isValueFound
变量,您可以执行以下操作:
isValueFound
为 true,并打破循环isValueFound
以确定它是找到还是未找到。此外,您还有一个学习二分搜索的好机会。 快乐编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.