數組:具有相同類型的若干變量按有序的形式組織起來的一種形式。這些按序排列的同類數據元素的集合稱為數組。
定義數組
int[] 變量名 = new int [n];
string[] myStringArray = new string[6];
int[] myArray = new int[] {1, 3, 5, 7, 9};
取值:int a = myArray[0];
一維數組
int [] array = new int [5]{1,2,3,4,5};
int [] array = new int[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
// array[5] = 6; 超出索引范圍
int a = array[2];
string [] ss = new string[3];
ss[0] = "1";
ss[1] = "2";
ss[2] = "3";
string b = ss[2];
輸入三個人名放入數組
string[] name = new string[3];
//Console.Write("請輸入第一個人名:");
//name[0] = Console.ReadLine();
//Console.Write("請輸入第二個人名:");
//name[1] = Console.ReadLine();
//Console.Write("請輸入第三個人名:");
//name[2] = Console.ReadLine();
for (int i = 1; i <= 3; i++)
{
Console.Write("請輸入第{0}個人名:",i);
name[i - 1] = Console.ReadLine();
}
//根據班級人數創建一個數組,要求每個人的姓名都要放進去
Console.Write("請輸入班級人數:");
int n = int.Parse(Console.ReadLine());
string [] name =new string[n];
for (int i = 0; i < n; i++)
{
Console.Write("請輸入第{0}個人的姓名:",i+1);
name[i] = Console.ReadLine();
}
Console.WriteLine("所有人員姓名輸入完畢,請按回車鍵查看所有人員姓名!");
Console.ReadLine();
Console.WriteLine();
for (int i = 0; i < n; i++)
{
Console.Write(name[i]+"\t");
}
Console.ReadLine();
從控制台輸入班級人數
將每個人的年齡放入數組,
將所有人的年齡求總和
求平均年齡
求年齡最大
Console.Write("請輸入班級人數:");
int n = int.Parse(Console.ReadLine());
int [] age = new int[n];
int sum = 0;
for (int i = 0; i < n; i++)
{
Console.Write("請輸入第{0}個人的年齡:",i+1);
age[i] = int.Parse(Console.ReadLine());
sum+=age[i];
}
Console.WriteLine(sum);
Console.WriteLine(sum/n);
int agemax = 0;
for (int i = 0; i < n; i++)
{
if (agemax < age[i])
{
agemax = age[i];
}
}
Console.WriteLine("最大年齡是:"+agemax);
//冒泡排序
for (int i = 0; i < n; i++)
{
for (int j = i; j < n-1; j++)
{
if (age[i] < age[j+1])
{
int zhong = age[i];
age[i] = age[j+1];
age[j+1] = zhong;
}
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(age[i]);
}
Console.ReadLine();
課後題
雙色球:從33個紅球中隨機六個,按從小到大順序排序,從16個藍球中選取一個。
int[] suiji = new int[6];
Random ran = new Random();
for (int i = 0; i < 6; i++)
{
bool b = true;
int a = ran.Next(1, 34);
for (int j = 0; j < 1; j++)
{
if(a==suiji[j])
{
b=false;
i--;
}
}
if(b)
{
suiji[i]=a;
}
}
Console.Write("紅球:");
for(int i = 0; i < 6; i++)
{
Console.Write(" "+suiji[i]);
}
Console.WriteLine();
for (int a = 0; a < 1; a++)
{
Random b = new Random();
int c = ran.Next(1,17);
Console.WriteLine("藍色:"+c);
}