首页 > 代码库 > 11、结构体、枚举

11、结构体、枚举

1、结构体结构体是一种特殊的集合,里面可以包含各种类型的数据。(结构体放在主函数的外面)public struct student//定义一个结构体,public是修饰符        {            public string name;            public decimal height;            public int age;        }         static void Main(string[] args)        {            student b=new student();//初始化结构体            b.name = "张三";            b.age = 22;            b.height =180;        }2、枚举枚举是一种特殊的集合,里面只存放常量。在多人开发项目时,可以方便统一名称。(枚    举放在主函数的外面)enum w:int//指定索引类型        {             a=3,//指定a的索引为3            b,            cuewirueiwuriuiriew,            d,            e=cuewirueiwuriuiriew//这样表示打印e就等于这一长串的代码,并且e没有索引        }        static void Main(string[] args)        {            Console.WriteLine(w.b);            Console.WriteLine((int)w.d);    }例题:        //输入学生人数,挨个输入姓名,身高,年龄,求平均年龄,然后按身高降序排列输出        public struct Student        {            public string Name;            public decimal NianLing;            public decimal Height;        }static void Main(string[] args)        {            Console.WriteLine("请输入人数:");            int n = int.Parse(Console.ReadLine());            decimal sumNianling = 0;            ArrayList arr = new ArrayList();            for (int i = 0; i < n; i++)            {                Student s = new Student();                Console.Write("请输入姓名:");                s.Name = Console.ReadLine();                Console.Write("请输入年龄:");                s.NianLing = decimal.Parse(Console.ReadLine());                sumNianling += s.NianLing;                Console.Write("请输入身高:");                s.Height = decimal.Parse(Console.ReadLine());                arr.Add(s);                }                for (int i = 0; i < n - 1; i++)                {                    for (int j = i + 1; j < n; j++)                    {                        Student s1 = (Student)arr[i];                        Student s2 = (Student)arr[j];                        if (s1.Height < s2.Height)                        {                            arr[i] = s2;                            arr[j] = s1;                        }                    }                }                Console.WriteLine("按身高排序后输出为:");                foreach (Student ss in arr)                {                    Console.Write("姓名:" + ss.Name);                    Console.Write("身高:" + ss.Height);                    Console.Write("年龄:" + ss.NianLing);                    Console.Write("\n");                }            Console.Write("平均年龄为:" + sumNianling / n);}    

 

11、结构体、枚举