簡體   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