本文以實(shí)例演示了C#各種數(shù)組的基本用法。主要包括:一維數(shù)組、二維數(shù)組、鋸齒型數(shù)組、長度不同的兩個(gè)數(shù)組、3行4列的矩陣數(shù)組等。
具體實(shí)現(xiàn)代碼如下:
using System;class ArrayApp{  public static void Main ( )  {    //一維數(shù)組用法:計(jì)算數(shù)組中奇偶數(shù)的個(gè)數(shù)    Console.WriteLine("一維數(shù)組演示:一維數(shù)組中的奇偶數(shù)個(gè)數(shù)");    int[ ] arr1 = new int[ ] {8, 13, 36, 30, 9, 23, 47, 81 };    int odd = 0;    int even = 0;    foreach ( int i in arr1 )       {      if ( i % 2 == 0 )        even ++;      else        odd ++;    }    Console.WriteLine("共有 {0} 個(gè)偶數(shù), {1} 個(gè)奇數(shù)。", even, odd);    //二維數(shù)組用法:m行n列的矩陣    Console.WriteLine("二維數(shù)組演示:3行4列的矩陣");    int[,] arr2 = new int[3,4] { {4,2,1,7}, {1,5,4,9}, {1,3,1,4} };    for ( int i = 0; i < 3; i++ )    {      for ( int j = 0; j < 4; j++ )      {        Console.Write(arr2[i,j] + "/t");      }      Console.WriteLine( );    }    //鋸齒型數(shù)組用法:元素個(gè)數(shù)不同的兩個(gè)數(shù)組    Console.WriteLine("鋸齒型數(shù)組演示:長度不同的兩個(gè)數(shù)組");    int[][] arr3 = new int[2][];    arr3[0] = new int[5] {1,3,5,7,9};    arr3[1] = new int[4] {2,4,6,8};    //   char[][] arr3 = new char[][] { {H,e,l,l,o}, {C,s,h,a,r,p} };    for ( int i = 0; i < arr3.Length; i++)    {      Console.Write("第{0}個(gè)數(shù)組是:/t",i+1);      for ( int j = 0; j < arr3[i].Length; j++ )      {        Console.Write(arr3[i][j]+ "/t");      }      Console.WriteLine();    }  }}新聞熱點(diǎn)
疑難解答
圖片精選