【问题标题】:Why should I type i++; outside the if block?为什么要输入 i++;在 if 块之外?
【发布时间】:2019-06-10 00:52:42
【问题描述】:

从数组中查找最大值时,我为什么要在 if 块之外键入 i++

int[] x = new int[] { 5, 7, -100, 400, 8 };

int i = 1;
int max;

max = x[0];

while (i < x.Length)
{
    if (x[i] > max)
    {
        max = x[i];
    }
    i++;
}
Console.WriteLine("MAX="+max);

【问题讨论】:

  • 谁/你应该说什么?
  • 因为否则,如果索引 i 处的值恰好大于 max(如果它位于 if 块内),您只会增加 i。我们希望在每次迭代时增加它。
  • 或者只是用Console.WriteLine("MAX="+(new[] { 5, 7, -100, 400, 8 }.Max());替换整个东西
  • 为什么你认为它应该在if里面?
  • 忽略负面因素。他们没有任何意义。如果你学到了一些新东西,今天是美好的一天!

标签: c# arrays if-statement while-loop max


【解决方案1】:

如果您只在if 块内增加i 内部,那么只要条件x[i] &gt; max 计算为falsei 就不会增加。由于我们使用i 作为要检查的数组元素的索引,x[i] 的值永远不会改变,因此循环将永远持续下去。

而且,就其价值而言,当您迭代数组时,for 循环更合适,因为它允许您在一个地方定义迭代变量、条件和增量:

int[] x = new int[] { 5, 7, -100, 400, 8 };
int max = x[0];

for(int i = 1; i < x.Length; i++)
{
    if (x[i] > max) max = x[i];
}

Console.WriteLine("MAX = " + max);

【讨论】:

    【解决方案2】:

    如果你在 if 块中使用 i++,你会进入一个无限循环:(

            while (i < x.Length)
            {
                if (x[i] > max)
                {
                    max = x[i];
                    i++;
                }                
            }
    

    假设这个数组 x = new int[] {9, 8}

    i = 1
    max = 9
    while ( 1 < 2 ){//and 1<2 is always true i=1 and x.length=2
         if ( 8 > 9){ //false, never enter
           max = 8
           i++  //never happens, i is always 1
         }    
    }
    

    如果索引有问题,可以使用“foreach”,而不是“while”

            int[] x = new int[] { 5, 7, -100, 400, 8 };
            int max;
    
            max = x[0];
            foreach (int elem in x)
            {
                if (elem > max)
                    max = elem;
            }
    
            Console.WriteLine("MAX=" + max);
            Console.ReadLine();
    

    【讨论】:

      【解决方案3】:

      假设您的数组是否包含以下值

      int[] x = new int[] { 2, 2, 2, 2, 2 };
      

      那么如何在if 块内使用i++ 找到最大值。您将陷入无限循环。

      【讨论】:

        【解决方案4】:

        如果你把它放在 if 块中,我只会在最大值增加时递增,如果数组中的每个值都大于之前的值,则让 while 循环永远运行。

        【讨论】:

        • 如果数组中的每个值都大于前一个值 这实际上是while 循环不会无限的唯一时间。
        猜你喜欢
        • 2021-07-11
        • 2018-05-13
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        相关资源
        最近更新 更多