在修改特定数字后如何反转数组中数字的顺序?

问题描述 投票:0回答:1

这是将4加到所有奇数的代码。

    int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 };
        int IncreaseOdd = 0;
        counter = 0;
        while (counter < 30)
        {
        IncreaseOdd = array[counter] % 2;
        if (IncreaseOdd == 1)
        {
         array[counter] += 4;
        }
         counter++;

这是应该以相反的顺序显示数组所有成员的代码,但它只对奇数进行显示。

counter = 0;

while (counter < 30)
{
 Array.Reverse(array);
 Console.WriteLine("\n{0}\t======\t\t{1}", counter, array[counter]);
 counter++;
 }
counter--;
c# arrays loops reverse
1个回答
0
投票

在将添加项应用于每个项目后,您需要反转一次:

    int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 };
    int IncreaseOdd = 0;
    counter = 0;
    while (counter < 30)
    {
    IncreaseOdd = array[counter] % 2;
    if (IncreaseOdd == 1)
    {
     array[counter] += 4;
    }
     counter++;

    // now reverse

    Array.Reverse(array);

    // now print the results

    counter = 0;
    while (counter < 30)
    {
     Console.WriteLine("\n{0}\t======\t\t{1}", counter, array[counter]);
     counter++;
    }
© www.soinside.com 2019 - 2024. All rights reserved.