12. C # basic organization (struct ),
Reference page:
Http://www.yuanjiaocheng.net/CSharp/Csharp-keys.html
Http://www.yuanjiaocheng.net/CSharp/csharp-interface.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-operators.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-if-else.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-ternary-operator.html
Struct
1. concept:
Struct is a data structure written outside the main function, which is composed of different types of data into a whole. The data in these combinations is interrelated.
2. Declaration method:
Struct name
{
Member variable (composed of type name + member name)
}
Example:
Public struct student // public is a modifier and can be left blank. The function scope is the entire namespace {public int Code; // defines the variable. Each variable is called the public string Name attribute of the struct; public string Sex; public int Age; public decimal Height ;}
3. Call method:
(1) initialize the struct (new)
(2) assign values to variables in the struct
For example:
// Continue to use the above struct definition student ss = new student (); ss. code = 101; ss. name = "zhangsan"; ss. sex = "nan"; ss. height = 173;
4. Use struct to optimize the code
---- Bubble sort ----
Question: Enter the number of students, enter the name, height, and age one by one, calculate the average age, and then sort the students in ascending order.
Idea: Create a struct containing the name, height, and age parameters, create a set, and put the struct types after each initialization into the set with three types of data through the for loop.
Answer:
Console. writeLine ("Number of input students:"); int n = int. parse (Console. readLine (); ArrayList ar = new ArrayList (); // create a set to fill data int sum = 0; for (int I = 0; I <n; I ++) {student ss = new student (); Console. write ("Enter name:"); ss. name = Console. readLine (); Console. write ("Enter age:"); ss. age = int. parse (Console. readLine (); Console. write ("Enter Height:"); ss. height = int. parse (Console. readLine (). trim (); ar. add (ss); // Add a student type data sum = sum + ss in the set. age; // calculate the total score} for (int I = 0; I <n; I ++) {for (int j = I; j <n; j ++) {// create an intermediate value, forcibly convert ar [I] and ar [j] to the student type, and then determine the height student s1 = (student) ar [I]; student s2 = (student) ar [j]; if (s1.Height <s2.Height) {ar [I] = s2; ar [j] = s1 ;}}} foreach (student a in ar) {Console. write ("name:" +. name); Console. write ("height:" +. height); Console. write ("Age:" +. age); Console. write ("\ n ");}