如何将使用嵌套for循环打印的二维数组居中

本文关键字:打印 二维数组 循环 for 嵌套 | 更新日期: 2023-09-27 18:25:50

如何将这个打印数组居中放置在控制台中间?

        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("0 1 2 3 4 5 6 7");
        Console.ResetColor();
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                Console.Write(BoardDisplay[j, i] + " ");
            }
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(i);
            Console.ResetColor();
        }

如何将使用嵌套for循环打印的二维数组居中

我在这个片段中介绍了一些格式化控制台输出的技术:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication9
{
    class Program
    {
        static int[,] BoardDisplay = new int[8, 8] { 
            { 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
            ,{ 1,2,3,4,5,6,7,8 }
        };
        static void Main(string[] args)
        {
            int space_for_each_cell = 5;
            var width = Console.WindowWidth;
            var height = Console.WindowHeight;
            int left = (width - (8* space_for_each_cell)) / 2;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.CursorLeft = left;
            for (int i = 0; i < 8; i++)
            {
                Console.Write("{0,"+space_for_each_cell+"}", i);
            }
            Console.WriteLine();
            Console.ResetColor();
            for (int i = 0; i < 8; i++)
            {
                Console.CursorLeft = left;
                for (int j = 0; j < 8; j++)
                {
                    Console.Write("{0,"+space_for_each_cell+"}", BoardDisplay[j, i]);
                }
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("{0,"+space_for_each_cell+"}",i);
                Console.ResetColor();
            }
            Console.ReadKey();
        }
    }
}

应用这个概念来满足您的需求。