反转数组 [英] reversing an array..

查看:68
本文介绍了反转数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是.NET的新手.我想反转一个数组,我已经完成了示例程序,但出现错误.

I am new to .NET. I want to reverse an array i have done sample program but i am getting error.

class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[6] { 1, 2, 3, 4, 5, 6, };
            //int[] b = new int[6];
            //int[] c = new int[6];
            Console.WriteLine("Elements in Array are:-");
            for (int i = a.Length; i >= 0; i--)
            {
                Console.WriteLine(a[i] + "");
            }
            Console.ReadLine();
        }


    }
}



我遇到这样的错误.
索引超出了数组的范围

谢谢.



i am getting error like this.
Index was outside the bounds of the array

thank you.

推荐答案

您正在艰难地做这件事.

您只需要一行代码:
You''re doing it the hard way.

You only need a single line of code:
class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[6] { 1, 2, 3, 4, 5, 6, };

            Array.Reverse(a);

            Console.WriteLine("Elements in Array are:");
            for (int i = 0; i < a.Length; i++)
            {
                Console.WriteLine(a[i] + "");
            }
            Console.ReadLine();
        }
    }
}


请记住,任何数组的长度都会告诉您其中有多少个元素.对于长度为10的数组,元素将从0到9进行索引.这就是您的代码抛出索引超出范围"错误的原因.


Keep in mind, the Length of any array will tell you how many elements there are in it. For for an array of Length 10, the elements will be indexed 0 through 9. That''s why your code was throwing an "Index out of bounds" error.


Hello

Hello

static void Main(string[] args)
     {
         int[] a = new int[6] { 1, 2, 3, 4, 5, 6, };

         Console.WriteLine("Elements in Array are:-");
         for (int i = a.Length; i > 0; i--)
         {
             Console.WriteLine(a[i - 1] + " ");
         }
         Console.ReadLine();
     }







Or

static void Main(string[] args)
{
    int[] a = new int[6] { 1, 2, 3, 4, 5, 6, };

    Console.WriteLine("Elements in Array are:-");
    for (int i = a.Length - 1; i >= 0; i--)
    {
        Console.WriteLine(a[i] + "");
    }
    Console.ReadLine();
}







Or

int[] a = new int[6] { 1, 2, 3, 4, 5, 6, };

int[] revers = a.Reverse().ToArray();

Console.WriteLine("Elements in Array are:-");
foreach (int i in revers)
{
    Console.WriteLine(i + "");
}


这篇关于反转数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆