3

嗨,我被告知要“编写代码,通过从末尾开始向后遍历数组并将搜索值与数组中的值。搜索后,如果找到该值,则打印“已找到该值”,否则打印“未找到该值”。

我了解随机数组的创建,但我被困在如何通过它向后工作并找到特定值。

这是到目前为止的代码

class Program
{
    static void Main(string[] args)
    {
        int[] myArray = new int[10];
        Random rand = new Random();

        for (int i = 0; i < myArray.Length; i++)
        {
            myArray[i] = rand.Next(19);
        }

    }
}

}

4

2 回答 2

1

要向后退,只需使用带有迭代器的 for 循环 to i--

for (int i = myArray.Length - 1; i >= 0; i---)
{
    if(// Check if myArray[i] equals the value to find)
    {
         // If it is the case, you can get out from the for loop with break
         break;
    }
}

for循环分为 4 个部分:

for (initializer; condition; iterator)
    body
  1. initializer循环中的第一次迭代之前执行(这里你想从数组中的最后一个索引开始myArray.Length - 1:)
  2. condition每次迭代进行评估,如果此条件为真,则进入 3(您想留在for循环中 while i >= 0),否则退出for循环
  3. body为满足条件的每次迭代执行
  4. iterator执行(在这里你想向后退,你想减少i
  5. 然后它回到2
于 2013-02-04T15:03:02.390 回答
1

使用从最大到最小索引开始的循环。

 bool found = false;
 for (int i = myArray.Length - 1; i >=0 ; i--) 
     if(myArray[i] == 5)
        found = true;
 if(found)
 {

 }
 else
 {

 }
于 2013-02-04T15:03:25.313 回答