【发布时间】:2020-12-24 12:50:55
【问题描述】:
我是一名学生,刚接触 c#,我尝试搜索一个元素并打印该元素的索引, 但我不知道为什么它不起作用。
这是我的代码
string temp = " ";
int hold;
const int SIZE = 5;
int[] a = new int[SIZE];
bool found = false;
int num;
//reading num from user
for (int i = 0; i < SIZE; i++)
{
a[i] = int.Parse(Interaction.InputBox("Enter the array values: "));
}
// print values
for (int i = 0; i < SIZE; i++)
{
temp = temp + a[i] + " ";
}
temp = temp + "\n";
MessageBox.Show("array values: \n" + temp);
// this part I want it
num = int.Parse(Interaction.InputBox("Enter the value to found "));
for (int j = 0; j < SIZE; j++)
{
if (a[j] == num)
{
MessageBox.Show("Searched value found in array");
}
}
MessageBox.Show("Searched value not found in array");
谢谢你
【问题讨论】:
-
else MessageBox.Show("Searched value not found in array");a) 该消息框需要在循环之后。 b)Array.IndexOf可能比您的循环方法更好。 -
for (int j = 0; j 这是不正确的。您应该遍历 array.length 以找到 num 或只使用 SIZE 来获取输入。使用此代码有时会得到结果,有时会出现错误或找不到任何东西
-
就像@Steve 说它必须是 SIZE 而不是 num
-
这样? @mjwills num = int.Parse(Interaction.InputBox("输入要找到的值")); for (int j = 0; j
-
Mpre 或更少,但如果你找到你的号码,你应该用 break 停止循环。然后,如果您找到它,您需要一些东西来不打印未找到的消息。在启动循环之前考虑 bool found = false;。如果您找到该值,请将其设置为 true。仅当您没有找到该值时,最后才打印失败消息