修改特定数字后,如何颠倒数组中数字的顺序?

时间:2019-10-31 19:27:16

标签: c# arrays loops reverse

这是将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--;

1 个答案:

答案 0 :(得分:0)

在对每个项目添加添加内容之后,您需要反转一次:

workout

此外,我会像这样升级您的代码:

    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++;
    }