C#结构体
结构体:
由多种简单类型,组合成一种复杂的类型。使用这种复杂的类型来解决生活中的实际例子。
一、结构体定义:
struct 结构体的名子
{
public 类型名 变量名;
.....
}
struct Student
{
public string NO;
public string Name;
public double YuWen;
public double ShuXue;
public double WaiYu;
public double ZongFen;
}
二、结构体的使用:
1.使用结构体来定义变量
Student s1 = new Student();
2.给结构体变量赋值。
s1.Name = "";
s1.NO = "";
3.给结构体变量取值。
s2.YuWen
三、复杂结构体。
使用结构体类型的成员变量,来组成更大的结构体。
1.先造个小的结构体
2.使用小的结构体来组合成更大的结构体。
struct Student
{
public string NO;
public string Name;
public ChengJi Score = new ChengJi();
public LianXiFangShi Contact = new LianXiFangShi():
}
struct LianXiFangShi
{
public string DianHua;
public string QQ;
public string YouXiang;
public string ZhuZhi;
}
struct ChengJi
{
public double YuWen;
public double ShuXue;
public double WaiYu;
public double ZongFen;
}
复杂结构体的定义:
Student s1 = new Student();
复杂结构体成员变量的使用。
s1.NO = "s001";
s1.Name = "张三";
s1.Contact.DianHua="18500002222";
s1.Contact.QQ="88888888";
s1.Contact.YouXiang="88888888@qq.com";
s1.Contact.ZhuZhi = "地球";
s1.Score.YuWen=89;
s1.Score.ShuXue=99;
s1.Score.WaiYu=79;
s1.Score.ZongFen = s1.Score.YuWen+s1.Score.ShuXue+s1.Score.WaiYu;
结构体应用实例
namespace 结构体_学生信息_
{
struct student
{
public int No;
public string Name;
public double Score;
}
class Program
{
static student[] input(student[] s)
{
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("输入第" + (i + 1) + "个学生的学号,姓名,c语言分数。以Tab建隔开,以回车结束");
string info = Console.ReadLine();
string[] mid = info.Split('\t');
s[i].No = Convert.ToInt32(mid[0]);
s[i].Name = mid[1];
s[i].Score = Convert.ToDouble(mid[2]);
}
return s;
}
static void output(student[] s)
{
double sum = 0, max = 0, min = 100;
int[] maxminno = new int[2];
string[] maxminname = new string[2];
double[] maxminscore = new double[2];
for (int i = 0; i < s.Length; i++)
{
if (s[i].Score > max)
{
maxminno[0] = s[i].No;
maxminname[0] = s[i].Name;
maxminscore[0] = s[i].Score;
max = s[i].Score;
}
if (s[i].Score < min)
{
maxminno[1] = s[i].No;
maxminname[1] = s[i].Name;
maxminscore[1] = s[i].Score;
min = s[i].Score;
}
sum = sum + s[i].Score;
}
Console.WriteLine("本班总分数为:" + sum);
Console.WriteLine("本班平均分为:" + sum / s.Length);
Console.WriteLine("本班最高分为:学号" + maxminno[0] + "姓名" + maxminname[0] + "分数" + maxminscore[0]);
Console.WriteLine("本班最低分为:学号" + maxminno[1] + "姓名" + maxminname[1] + "分数" + maxminscore[1]);
}
static void PaiXun(student[] s)
{
for (int i = 1; i <= s.Length - 1; i++)
{
for (int j = 1; j <= s.Length - i; j++)
{
if (s[j].Score > s[j - 1].Score)
{
student temp = s[j];
s[j] = s[j - 1];
s[j - 1] = temp;
}
}
}
Console.WriteLine("名次 学号 姓名 成绩");
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine((i + 1) + "\t" + s[i].No + "\t" + s[i].Name + "\t" + s[i].Score);
}
}
static void Main(string[] args)
{
student[] s = new student[5];
s = input(s);
output(s);
PaiXun(s);
}
}
}