c#例题:输入学生的学号,姓名,分数,然后根据分数进行排序再输出最终结果。重点学习用结构体定义数组的表达方式

时间:2023-01-08 08:38:37
 class Program
    {
        struct student     //定义一个结构体
        {
            public int code;
            public string name;
            public int fenshu;
        }
        static void Main(string[] args)
        {
            Console.Write("请输入人数:");
            int renshu = Convert.ToInt32(Console .ReadLine ());
            student[] r = new student[renshu];     //定义一个结构体学生类型的数组
            for (int i = 0; i < renshu ; i++)
            {
                Console.Write("情输入第"+(i+1)+"个人的学号:");
                r[i].code = Convert.ToInt32(Console .ReadLine ());   //注意用结构题体义的数组如何表达
                Console.Write("请输入第"+(i+1)+"个人的姓名:");
                r[i].name = Console .ReadLine ();
                Console.Write("请输入第"+(i+1)+"个人的分数:");
                r[i].fenshu = Convert.ToInt32(Console .ReadLine ());
            }
            for (int i = 0; i < renshu ; i++)
            {
                for (int j = i; j < renshu -1; j++)
                {
                    if (r[i].fenshu <r[j+i].fenshu )   //用分数进行排序
                    {
                       student  temp = r[i];          
                       r[i] = r[j + 1];
                       r[j + 1] = temp;

                    }
                }
            }
            Console.WriteLine("排序后顺序为:");
            for (int i = 0; i <renshu ; i++)  //输出最终结果
            {
                Console.WriteLine("学号"+r[i].code +"\t姓名"+r[i].name +"\t分数"+r [i].fenshu );
            }
            Console.ReadLine();
        }
    }
}