你的位置:首页 > ASP.net教程

[ASP.net教程]C#ArrayList集合——小例题


用两种方法编写题目:输入姓名,语文分数,数学分数,英语分数到集合,求语文总分,数学平均分,英语最高分以及英语最高分是谁。
法一:一个集合的做法
Console.Write("输入总人数:");
int s = int.Parse(Console.ReadLine());
ArrayList ss = new ArrayList();
for (int i = 0; i < s; i++)
{
Console.Write("第" + (i + 1) + "的姓名:");
ss.Add(Console.ReadLine());
Console.Write("第" + (i + 1) + "英语成绩:");
ss.Add(Console.ReadLine());
Console.Write("第" + (i + 1) + "数学成绩:");
ss.Add(Console.ReadLine());
Console.Write("第" + (i + 1) + "语文成绩:");
ss.Add(Console.ReadLine());
}
for (int i = 1; i <= 4 * s; i += 4)
{
for (int j = i; j <= 4 * s - 4; j += 4)
{
if (double.Parse(ss[i].ToString()) < double.Parse(ss[j + 4].ToString()))
{
double ying = double.Parse(ss[i].ToString());
ss[i] = ss[j + 4];
ss[j + 4] = ying;
string xing = ss[i - 1].ToString();
ss[i - 1] = ss[j + 3];
ss[j + 3] = xing;
double shu = double.Parse(ss[i + 1].ToString());
ss[i + 1] = ss[j + 5];
ss[j + 5] = shu;
double yu = double.Parse(ss[i + 2].ToString());
ss[i + 2] = ss[j + 6];
ss[j + 6] = yu;
}
}
}
for (int i = 0; i < 4 * s; i++)
{
Console.WriteLine(ss[i]);
}
double sum1 = 0;
double sum2 = 0;
for (int i = 0; i < 4 * s; i+=4)
{
sum1 += double.Parse(ss[i + 2].ToString());
sum2 += double.Parse(ss[i + 3].ToString());
}
Console.WriteLine("数学总分:" + sum1);
Console.WriteLine("语文平均分:" + (sum2 / s));
Console.WriteLine("英语分数最高的人是:" + ss[0] + ",分数是:" + ss[1]);
Console.ReadLine();
法二:四个集合的做法
Console.Write("输入总人数:");
int s = int.Parse(Console.ReadLine());
ArrayList ss = new ArrayList();
ArrayList rr = new ArrayList();
ArrayList tt = new ArrayList();
ArrayList yy = new ArrayList();
for (int i = 0; i < s; i++)
{
Console.Write("第" + (i + 1) + "的姓名:");
ss.Add(Console.ReadLine());
Console.Write("第" + (i + 1) + "英语成绩:");
rr.Add(Console.ReadLine());
Console.Write("第" + (i + 1) + "数学成绩:");
tt.Add(Console.ReadLine());
Console.Write("第" + (i + 1) + "语文成绩:");
yy.Add(Console.ReadLine());
}
for (int i = 0; i < s; i++)
{
for (int j = i; j < s - 1; j++)
{
if (double.Parse(rr[i].ToString()) < double.Parse(rr[j + 1].ToString()))
{
double ying = double.Parse(rr[i].ToString());
rr[i] = rr[j + 1];
rr[j + 1] = ying;
string xing = ss[i].ToString();
ss[i] = ss[j + 1];
ss[j + 1] = xing;
double shu = double.Parse(tt[i].ToString());
tt[i] = tt[j + 1];
tt[j + 1] = shu;
double yu = double.Parse(yy[i].ToString());
yy[i] = yy[j + 1];
yy[j + 1] = yu;
}
}
}
for (int i = 0; i < s; i++)
{
Console.WriteLine(ss[i] + "\t");
Console.WriteLine(rr[i] + "\t");
Console.WriteLine(tt[i] + "\t");
Console.WriteLine(yy[i] + "\t");
}
double sum1 = 0;
double sum2 = 0;
for (int i = 0; i < s; i++)
{
sum1 += double.Parse(tt[i].ToString());
sum2 += double.Parse(yy[i].ToString());
}
Console.WriteLine("数学总分:" + sum1);
Console.WriteLine("语文平均分:" + (sum2 / s));
Console.WriteLine("英语分数最高的人是:" + ss[0] + ",分数是:" + rr[0]);
Console.ReadLine();