C#基礎 數組、二維數組


數組:相同數據類型的元素按一定順序排列的集合。是一組變量

作用:操作大量數據    

數組的定義

1、數組里面的內容必須是同一類型

2、數據必須有長度限制                               //  定義時限定長度,往后無法更改

一維數組

1、表達式

(1)指定長度

 數據類型[ ] 變量名 = new 數據類型[長度];

//定義一個有五個變量的string類型數組
string [ ] s  = new atring [ 5 ];    
s [0] = "aaa";  //索引 0 所對應的字符串值是 aaa
s [1] = "bbb";  
     ......            //最多定義五個                                                                               

(2)指定內容

     數據類型[ ]變量名= new 數據類型[ ] { "  ", "  ", "  ", "  " };    

string[] sss = new string[ ] { "aaa", "bbb", "ccc", "ddd", "eee" };
 //花括號有多少就默認數組長度多少。

(3)指定長度跟能容

string[] sss = new string[5] { "aaa", "bbb", "ccc", "ddd", "eee" };

 

2、一維數組的賦值:  

   變量名[索引] = 值;

3、一維數組的取值: 

   值 = 變量名[索引];                     

 int[  ] a = new int[] { 1,5,7};
 int b = a[ 0 ];        //賦值
 a[0] = a[a.Length - 1];
 a[a.Length - 1] = b;
  for (int i = 0; i < a.Length; i++)
{
   Console.WriteLine(  a[i]  );   // 取值

 

實例;

// 將用戶輸入的內容放入數組中並輸出。
  string [ ] ss = new string [ 5 ] ;
  for ( int i = 0 ; i < ss.Length ; i++ );
  {
     Console.Write("請輸入第“+ i +1+”個內容");
      ss [ i ] = Console.ReadLie();
  }
  for ( int i = 0 ; i < ss.Length ; i++ );
  {
      Console.WriteLine( ss [ i ] );
  }

//簡單的抽獎設計
string [ ] sss = new string [ ] {"升官","發財","娶老婆","換車","換房","換新顏"};
   Random r = new Random();
   int a = r . Next( 0, sss.Langth );
   Console.WriteLine( sss[ a ] );

// 讓數據停一會
  for (int i =0 ; i<10 ;i++)
{
  Console.WriteLine(i);
  System.Threading.Thread.sleep(500); //讓數字有時間間隔的打印出來    括號內為毫秒  1000毫秒= 1 秒
  Console.Clear(); //見打印結果清除  
}
  

 

 

二維數組 

在二維數組中每一個一維數組的長度必須是一樣的

表達式:

 string[ , ] 變量名 = new string [ 一維數組個數 , 一維數組中變量個數 ]; 

 

//strss這個個二維數組有2個一維數組,每一個一維數組中有3個變量  
string[ , ] strss = new string[ 2 , 3 ]{ {"a","b","c"} ,{"aa","bb","cc"} }         
                

 

 

三維數組
表達式:

string[ , , ] 變量名 = new string [ 二維數組個數 , 每個二維數組中的一維數組個數,一維數組中變量個數 ]; 

 

//有2個二維數組,每一個二維數組中有3個一維數組,每一個一維數組中有4個變量
 string[,,] strsss = new string[2,3,4];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM