2013-11-25 3 views
-1

배열을 채우고 배열을 콘솔에 표 형식으로 표시해야합니다. 여기 2D 배열에 대한 테이블을 어떻게 표시합니까?

는 내가 지금까지 무엇을 가지고 :
static void Main() 
    { 
     //Declare variables, strings and constants. 

     const int ROWS = 10; 
     const int COLS = 5; 
     const int MIN = 1; 
     const int MAX = 100; 
     int total = 0; 

     int[,] numbers = new int[ROWS, COLS]; 
     Random rand = new Random(); 

     //Populate the array 

     for (int r = 0; r < ROWS; ++r) 
     { 
      for (int c = 0; c < COLS; ++c) 
      { 
       numbers[r, c] = rand.Next(MIN, MAX + 1);      
      } 
     } 

     //Display the array to console (table format) 

     for (int r = 0; r < numbers.GetLength(0); ++r) 
     { 
      for (int c = 0; c < numbers.GetLength(1); ++c) 
      { 
       Console.Write("{0,6} ", numbers[r, c]); 
       if (c % 5 == 0) Console.WriteLine(); 

      } 
     } 

내가 이렇게

, 내 디스플레이 1로하고, 10x5 테이블에 대해 제대로 정렬되지 않습니다 오프 경우.

+0

그리고 귀하의 질문은 무엇입니까? – zerkms

답변

0

를 인쇄 최초의 출력, R = 0, C = 0, 그래서 열 인덱스 경우 확인할 수 있다고 공지 사항

if (c + 1 == COLS) Console.WriteLine(); 

또 다른 방법은 모든 C 후에 새로운 라인을 인쇄하는 것이다 플러스 하나 c + 1는 지정된 열 카운트 COLS 같은지, 새로운 라인을 작성 olumns가 인쇄됩니다.

for (int r = 0; r < numbers.GetLength(0); ++r) 
{ 
    for (int c = 0; c < numbers.GetLength(1); ++c) 
    { 
     Console.Write("{0,6} ", numbers[r, c]); 
    } 
    Console.WriteLine(); 
} 
0

이는 다음 라인으로 발생합니다

if (c%5 == 0) Console.WriteLine(); 

는 새로운 라인을