首页 > 代码库 > 一维数组

一维数组

[] 是定义数组,与索引号  {} 中的是数组元素

一维数组

定义数组   int[] i = new int[数组中有几个元素];

       也可以写成 int[] i = new int[3]{1,2,3};【数组的下标都是从零开始的】

一维数组取值   如:int[] i = new int[3]{1,2,3};

    int x=i[2];     输出x则为 3.

 

Foreach(定义个变量 in  数组名)

{

输出语句;

}

Foreach 只能在数组中使用

 

二维数组

定义二维数组        int[,] er = new int[2, 3] {{1,2,3},{4,5,6}};//可以理解成,两个一维数组,每个一维数组中有三个元素

二维数组取值可以写成

            Console.WriteLine(er[1,1]);

二维数组赋值   如  er[0,0]=1;

 

例题:

  输入10个人的分数,去掉两个最高两个最低,求平均分

    Console.Write("请输入人数:");
            int renshu = int.Parse(Console.ReadLine());
            int[] chengji = new int[renshu];
            if (renshu >= 5)
            {
                for (int h = 1; h <= renshu; h++)
                {
                    Console.Write("请输入第" + h + "个人的成绩");
                    chengji[h - 1] = int.Parse(Console.ReadLine());
                }
                for (int i = 0; i < renshu; i++)               //冒泡排序,成绩由大到小排好
                {
                    for (int j = i+1; j < renshu ; j++)
                    {
                        if (chengji[i] < chengji[j])
                        {
                            int zhong = 0;      
                            zhong = chengji[i];
                            chengji[i] = chengji[j];
                            chengji[j] = zhong;
                        }
                    }
                }
                int he = 0;                            
                for (int i = 0; i <= (renshu - 1); i++)     //算出总的成绩
                {

                    he = he + chengji[i];
                }
                double pj = (he - chengji[0] - chengji[1] - chengji[renshu - 2] - chengji[renshu - 1]) / (renshu - 4);
                Console.WriteLine("去掉两个最高分{0}、{1},去掉两个最低分{2}、{3},最后平均成绩是:{4}", chengji[0], chengji[1], chengji[renshu - 2], chengji[renshu - 1], pj);
            }
            else
            {
                Console.WriteLine("输入的人数要大于等于5!!!");
            }         
             Console.ReadKey();

一维数组