为什么我要输入 i++;在 if 块之外?

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


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);


慕侠2389804
浏览 78回答 4
4回答

翻过高山走不出你

如果您只在块内递增,i 那么if只要条件x[i] > max评估为false,i就不会递增。并且由于我们使用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++){&nbsp; &nbsp; if (x[i] > max) max = x[i];}Console.WriteLine("MAX = " + max);

烙印99

如果你 i++ 在 if 块内,你进入一个无限循环:(&nbsp; &nbsp; &nbsp; &nbsp; while (i < x.Length)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (x[i] > max)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = x[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }假设这个数组 x = new int[] {9, 8}i = 1max = 9while ( 1 < 2 ){//and 1<2 is always true i=1 and x.length=2&nbsp; &nbsp; &nbsp;if ( 8 > 9){ //false, never enter&nbsp; &nbsp; &nbsp; &nbsp;max = 8&nbsp; &nbsp; &nbsp; &nbsp;i++&nbsp; //never happens, i is always 1&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;&nbsp;}如果索引有问题,可以使用“foreach”,而不是“while”&nbsp; &nbsp; &nbsp; &nbsp; int[] x = new int[] { 5, 7, -100, 400, 8 };&nbsp; &nbsp; &nbsp; &nbsp; int max;&nbsp; &nbsp; &nbsp; &nbsp; max = x[0];&nbsp; &nbsp; &nbsp; &nbsp; foreach (int elem in x)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (elem > max)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = elem;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("MAX=" + max);&nbsp; &nbsp; &nbsp; &nbsp; Console.ReadLine();

holdtom

让我们假设您的数组是否包含以下值int[]&nbsp;x&nbsp;=&nbsp;new&nbsp;int[]&nbsp;{&nbsp;2,&nbsp;2,&nbsp;2,&nbsp;2,&nbsp;2&nbsp;};i++那么如何在块内找到最大值。您if将陷入无限循环。

人到中年有点甜

如果将它放在 if 块中,我只会在最大值增加时递增,如果数组中的每个值都大于之前的值,则让 while 循环永远运行。
打开App,查看更多内容
随时随地看视频慕课网APP