将迭代中的当前元素与数组中的所有以下元素进行比较 - for循环

问题描述 投票:0回答:1
int[] num = new int[] { 20, 19, 8, 9, 12 };

对于上面数组中的示例,我需要比较:

  • 元件20具有元件19,8,9,12
  • 元素19与8,9,12
  • 元素8与9,12
  • 元素9与12
c# arrays loops console-application nested-loops
1个回答
2
投票

两个循环:

// Go through each element in turn (except the last one)
for (int i = 0; i < num.Length - 1; i++)
{
    // Start at the element after the one we're on, and keep going to the
    // end of the array
    for (int j = i + 1; j < num.Length; j++)
    {
        // num[i] is the current number you are on.
        // num[j] is the following number you are comparing it to
        // Compare num[i] and num[j] as you want
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.