【问题标题】:Searching a one-dimensional array for a particular value在一维数组中搜索特定值
【发布时间】: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。仅当您没有找到该值时,最后才打印失败消息

标签: c# arrays search


【解决方案1】:

考虑:

    bool isFound = false;
    for (int j = 0; j < a.Length; j++)
    {
        if (a[j] == num)
        {
            isFound = true;
        }
    }

    if(isFound) 
    {

    }
    else
    {

    }

完成它..

然后考虑当你找到你想要的东西时如何停止循环(效率:不要继续搜索你已经找到的东西)

【讨论】:

    猜你喜欢
    • 2019-09-13
    • 2022-01-10
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多