繁体   English   中英

在一维数组中搜索特定值

[英]Searching a one-dimensional array for a particular value

我是一名学生,是 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");

谢谢你

考虑:

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

    if(isFound) 
    {

    }
    else
    {

    }

干掉就行了。。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM