【发布时间】:2017-05-15 13:59:07
【问题描述】:
我正在创建一个循环来从数组中搜索一个值。如果我找到它,将打印该位置,如果它不是“没有这样的数字”将被打印。 但是,如果我有几个相同的号码,我将只收到一个,然后我就结束了循环。如果数组中的数字相同,我如何获得控件? 我最好的尝试以无限循环或从一开始就完成的循环结束。
static public void Searching(int[] arr)
{
string x = "yes";
Console.WriteLine("Enter please searching number");
while (x == "yes")
{
bool found = false;
int target = Convert.ToInt32(Console.ReadLine());
int searchkey = target;
int mid = 0, first = 0, last = arr.Length - 1;
while (!found && first <= last)
{
mid = (first + last) / 2;
if (target == arr[mid])
found = true;
else
{
if (target > arr[mid])
{
first = mid + 1;
}
if (target < arr[mid])
{
last = mid - 1;
}
}
}
String foundmsg = found
? "Item " + searchkey + " was found at position " + mid
: "Item " + searchkey + " was not found";
Console.WriteLine(foundmsg);
Console.WriteLine("would you like to find another number?");
x = Console.ReadLine();
}
}
【问题讨论】:
-
我猜英语不是你的第一语言。老实说,我不确定您为什么要使用循环。如果您将数字数组转换为字符串,然后使用
.IndexOf(inputNumber),您将得到您想要的。我错过了语言障碍吗? -
你可能想改写你的第一句话,因为很多人觉得这个词令人反感。
-
我刚刚编辑了它(也做了代码格式化等),但现在有一个待编辑的。我的编辑超出了窗口-_-
-
@cdove 没关系,我知道我可以使用那个函数,但那是我的课堂任务,所以我应该只使用循环。
-
乍一看,您的代码对我来说还不错。您可以包含导致您进入无限循环的 input 吗?编辑:你是说如果你有多次相同的数字,你想输出每个匹配数字的位置?
标签: c# loops infinite-loop binary-search