数组声明:
- 整数类型:int [ ] 数组名 = {1,2,3}
- 浮点类型:double [ ] 数组名 = { }
或者 double [ ] 数组名;
数组名 = { } ;
- 字符串类型:string [ ] 数组名 = { }
声明语法:
- int [ ] 数组名 = new int [数组长度] (默认值为0)
- 数组名 = new int [ ] { 1,2,3,4,5 }
数组声明:
或者 double [ ] 数组名;
数组名 = { } ;
声明语法:
数组的赋值
int[]内为数组的长度
不指定的情况下按照数据的个数来判定
不同行ages = new int {1,1,1,1,1};
ages[6]=20;数组中的第六位等于20
赋值方式:
1:int [] 数据={,,};
2:数据=new int[赋值];(默认值)
3:数值=new int[]{ , , ,}
4:数值=new int[数组大小]{ , , ,}
数组的赋值方式:
1、int[] a = new int[]{123,412,143,2}
这种方式可以换行赋值,没固定索引
2、int[] a = {15,651,814,31,1,3}
这种方式不能换行
3、int[] a = new int[4]{11,51,48,30,47}
这种方式可以换行,也固定了索引(下标)。
4、int[] a = new int[6];
这种方式固定了数组6个,且这6个为默认值数组“数字数组的默认值为“0””
int[] arr = new int[];
这样创建数组时数组中的数据有默认值, 根据数组的数据类型不同, 默认值不同。
此处与java相同
int[] arr3 = new int[3]{1,2,3};
C# 这样定义数组时可以指定数组长度, 数组长度和后面的数据长度必须相同。
此处与java不相同, java不能指定长度的同时进行赋值数据。java如:
int[] arr4 = new int[4];
int[] arr5 = new int[]{2, 3, 5, 6, 7};
数组的赋值:
1:int[] a={1,2,3,4,5};
2: a=new int [x];
3:a=newint [6]{1,2,3,4,5,6};
声明数组:
数据类型[] 数组名;
初始化数组:
数组名 =new 数据类型[];
初始化的元素类型与声明时的类型必须相同。
例: int[] array01 = new int[5];
string[] array02 = new string[3];
怎么遍历一个数组?
int[] temp = new int[5] { 5, 6, 7, 8, 9 };
for(int a = 0; a < 5;a++)
{
Console.WriteLine(temp[a]);
}
2. foreach遍历数组:
int[] temp;
temp = new int[] { 5, 56, 7, 89, 23, 46, 459, 2, 77, 85, 65 };
foreach(int i in temp)
{
Console.Write(i + " ");
}
int i 为临时变量,随着遍历的进行,i中的数值也是变化的,所以叫做临时变量。
foreach只能正序遍历,如果想倒序遍历数组可以用for或while循环语句来写。
3. 获得位置数组中数值的长度,也就是数值的个数。
int[] ages = {2,3,4,5,6,7,8,9};
Console.Write(ages.Length);
输出结果为:8 这样就可以获得数组中数值的个数了。
例如:
int[] temp;
temp = new int[] { 5, 56, 7, 89, 23, 46, 459, 2, 77, 85, 65 };
Console.WriteLine(temp.Length);
for(int i = 0; i < temp.Length; i++)
{
Console.Write(temp[i] + " ");
}
temp.Length可以直接用,用以表示数组中数值的个数。
数组赋值方式:
int[] ages = new int[10];
int[] ages;
ages = new int[] {11,22,33,44};
int[] a ={1,22,333};
int[] ag = new int{1,22,333};
int[] age = new int[]{1,22,333};
int[] ages = new int [3]{1,22,333};
第八十三课 数组的使用
1.数组可以先声明再赋值的。
例如:
char[] temp;
temp={a,b,c,d,e,f,g};
2.数组赋值方法:
①第一种声明与赋值方法:
(比较直观切普通的方法)
int[] ages = {32,54,68,51,23,54,65,45};
这样的方式创建声明和赋值需要放在同一行,如果想用两行来创建声明和赋值需要用new的方式了。
②第二种声明预付制方法:
int[] ages;
ages = new int[10];
先声明数组变量,变量名为ages;
new int[10]; new为创建的意思,int[10]意思为长度为10的。整体意思是,创建一个长度为10的int类型。
也可以缩减写出来
int[] ages = new int[10];
③第三种声明与赋值方法:
int[] ages;
ages=new int[]{12,5,48,68,12,6};
第三种方法比较第一种方法多个new,在数值声明中,基本都用new来创建的,因为数组是引用类型的创建方法,它和int的基本类型的变量存储的位置不一样。
④第四种声明与赋值方法:
int[] ages;
ages = new int[5]{2,5,6,7,8};
在int[5]添加了具体赋值长度,如果不在int[]中添加数字来限制长度,那么系统会默认后面{ }中有多少就是多长了,可以随便写多少数值。如果限制了长度,也有好处,不能随便写了呗。
3.没有赋值就说明是默认值
int[] ages;
ages = new int[10];
这样创建长度为10的ages,其中默认10个赋值数值都是0。
4.数组中的数值修改。
例如:
int[] ages = {12,16,20,13,15,17,18,18};
ages[4]=16;
Console.WriteLine(ages[4]);
输出为:16