取两个数组:
int[] arr2 = new int[5]; int[] arr3 = new int[5];
现在,如果数组元素除以2得到的余数为0,则为偶数。获取这些元素并添加另一个数组。这遍历数组的长度:
if (arr1[i] % 2 == 0) { arr2[j] = arr1[i]; }
在else条件下,您将获得奇数元素。将它们添加到单独的数组中,并分别显示它们,如以下示例所示:
using System; namespace Demo { public class Program { public static void Main(string[] args) { int[] arr1 = new int[] { 77, 34, 59, 42, 99 }; int[] arr2 = new int[5]; int[] arr3 = new int[5]; int i, j = 0, k = 0; for (i = 0; i < 5; i++) { if (arr1[i] % 2 == 0) { arr2[j] = arr1[i]; j++; } else { arr3[k] = arr1[i]; k++; } } Console.WriteLine("Even numbers..."); for (i = 0; i < j; i++) { Console.WriteLine(arr2[i]); } Console.WriteLine("Odd numbers..."); for (i = 0; i < k; i++) { Console.WriteLine(arr3[i]); } } } }
输出结果
Even numbers... 34 42 Odd numbers... 77 59 99