C#:利用结构体数组完成简单信息输入、计算
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace norm_program
{
class Program
{
struct STU
{
public string Sname;
public Int64 Snum;
public double Saverage, Stotal;
public int Schinese, Smath, Senglish;
};
static void Main()
{
Console.WriteLine("请以“学号 姓名 语文成绩 数学成绩 英语成绩”顺序录入学生信息,各学生信息以空格符分开:");
string stu = Convert.ToString(Console.ReadLine());
Console.WriteLine("\n");
string[] stu_array = stu.Split(' ');//用split方法对输入的字符串以空格符划分,并存储进一维数组中;
STU[] StuInfor = new STU[stu_array.Length / 5];
for (int i = 0,j=0 ; i < stu_array.Length/5 && j % 5 == 0 && (j+1) < stu_array.Length; ++i,j = j + 5)
{
StuInfor[i].Snum = Convert.ToInt64(stu_array[j]);
StuInfor[i].Sname = stu_array[j + 1];
StuInfor[i].Schinese = Convert.ToInt16(stu_array[j + 2]);
StuInfor[i].Smath = Convert.ToInt16(stu_array[j + 3]);
StuInfor[i].Senglish = Convert.ToInt16(stu_array[j + 4]);
StuInfor[i].Stotal = StuInfor[i].Schinese + StuInfor[i].Smath + StuInfor[i].Senglish;
StuInfor[i].Saverage = StuInfor[i].Stotal / 3;
}
int max=0;
for (int j = 1; j < (stu_array.Length / 5); ++j)
if (StuInfor[max].Stotal < StuInfor[j].Stotal)
max = j;
for ( int i = 0 ; i < (stu_array.Length / 5); ++i)
Console.WriteLine("{0} {1} {2} {3} {4} {5} {6:f2}\n", StuInfor[i].Snum, StuInfor[i].Sname, StuInfor[i].Schinese,
StuInfor[i].Smath, StuInfor[i].Senglish, StuInfor[i].Stotal, StuInfor[i].Saverage);
Console.Write("总分最高记录为{0} {1} {2} {3} {4} {5} {6:f2}", StuInfor[max].Snum, StuInfor[max].Sname, StuInfor[max].Schinese,
StuInfor[max].Smath, StuInfor[max].Senglish, StuInfor[max].Stotal, StuInfor[max].Saverage);
Console.ReadLine();
}
}
}
这也不是太难,但是还是陆陆续续玩了一天,这是为啥呢?原因有三:
- 采用的是不换行输入。从第一个学生的学号信息开始一直连续输入到最后一个学生的英语成绩,中间仅用空格分开,后用slip方法将录入信息存入一维字符串数组stu_array当中;
- 没有提前限定学生人数,以及对应的信息字符串长度。因此,在运用结构体数组实现对数组成员的赋值时,需要格外考虑数组stu_array下标、以及结构体数组StuInfor下标的遍历取值;
- 涉及到数组下标就得注意下标的取值界限情况。
虽然耗费了一点时间,但是通过编写这个简单的程序,收获还是不少的,比如说:
- 我可以采用结构体数组的方法实现对结构体成员中不同类型数据进行各自赋值,并且由于其自身就是数组,那么就可以赋不同的值;
- 再是,结构体的归纳性,可以使得数据的描述与实际应用很相一致。
(以上纯属个人看法)