交错数组(求平均数)

交错数组是元素为数组的数组。交错数组元素的维度和大小可以不同。交错数组有时称为“数组的数组”。以下示例说明如何声明、初始化和访问交错数组。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace staggerArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int [][] a=new int[5][]; 
            Random ran = new Random();
            int[] sum = new int[a.Length];
            double num = 0;
            int i , temp=0;
            for ( i = 0; i < a.Length;i++ )
            {
               a[i] = new int[ran.Next(5)+1];
                if(temp < a[i].Length){
                    temp = a[i].Length;
                }
            } 
            for (i = 0; i < a.Length; i++)
            {
                Console.Write("第{0}行:", i + 1);
                for(int j = 0;j < a[i].Length;j++){
                    a[i][j] = ran.Next(100)+1;
                    Console.Write(a[i][j]);
                    Console.Write("\\t");
                    sum[i] += a[i][j];
                }
                for (int n = 1; n <= temp - a[i].Length; n ++ )
                {
                    Console.Write("\\t");
                }
                num = (double)sum[i] / a[i].Length;
                Console.Write("平均值:{0:f2}",num);
                Console.WriteLine();
            }
        }
    }
}
0 条评论