【问题标题】:Linear search in c# [closed]c#中的线性搜索[关闭]
【发布时间】:2015-11-22 17:42:48
【问题描述】:

大家好,我是编码初学者,我正在使用 c# 进行线性搜索,但不知道如何让它显示在搜索时找到的数字的数组中。它只是让它说它在最后一个数组上。这是我的代码:

Random Generator = new Random();
int[] array = new int[100];
int count = 0;
for (int i = 0; i < array.Length; i++)
{
    array[i] = Generator.Next(1, 100);
    count++;
}
Console.WriteLine("Write a number between 1-100 and see if it's in a array and in what array.");
int guess = Convert.ToInt32(Console.ReadLine());

bool exists = array.Contains(guess);
if (exists)
{
    Console.WriteLine("Your number {0} is in the {1}th Array.", guess, count);
}
else
{
    Console.WriteLine("Your number {0} does not match any number in any of the Arrays.", guess);
}

Console.ReadKey();

我的 count int 有问题,但我不知道该怎么办。提前致谢。

【问题讨论】:

  • 欢迎来到 Stack Overflow。 出了点问题到底是什么意思?出乎意料的结果?你想要什么结果呢?请阅读How to Ask 几次。
  • 您的文字与您的代码完全不匹配。你有 one 数组。你所有的输出文本都暗示你想要多个数组。
  • @nvoigt 数组 == 数组元素
  • @snoodel :您实际上并没有在这里自己进行线性搜索,只是调用 Contains() 方法。作为一个小练习。
  • 我想要完成的是,如果在其中一个数组中找到 1-99 之间的数字,然后让程序判断它是在哪个数组中找到的。

标签: c# linear-search


【解决方案1】:

我想你在找Array.IndexOf

Int index = Array.IndexOf(amountOfArrays,guess);
If (index == -1)
{
    // not found
}
else 
{
    // found
}

Count++ 将是最后一个。你怎么会期望它是别的东西?

【讨论】:

  • 这个问题的可能解释,但是amountOfArrays这个名字是从哪里来的?提问者使用标识符array
  • @JeppeStigNielsen 这只是一个变量名。它显然用作数组大小。我怀疑英语不是 OP 的母语。
  • 感谢您的帮助,但我对应该在哪里使用它一无所知?你的意思是不是 array.Contains?
  • Array.IndexOf 会给你位置。使用它而不是计数。
  • 论据 1:无法从 'int' 转换为 System.Array 错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多