【问题标题】:How can I draw a diagonal line with Console.SetCursorPosition c#?如何使用 Console.SetCursorPosition c# 绘制对角线?
【发布时间】:2019-08-18 16:00:05
【问题描述】:

我需要做一个函数,接收3个元素:行首的水平和垂直位置,以及它的长度,并绘制向左下降的对角线。我不明白我怎么能做对角线。我已经做了一个循环来做一条水平线,但我不知道我需要改变什么来画一条对角线。

对于水平线,我已经做到了:

    static void LigneHorizontale(int posh, int pov, int longueur)
    {

            for (int i = 0; i < longueur; i++)
            {
                Console.SetCursorPosition(posh+i, pov);
                Console.WriteLine("-");
            }
    }

【问题讨论】:

  • 水平线只是一个用破折号填充的较长字符串。喜欢 ” - - - - - - ”。您可以生成带有您选择的字符和长度的字符串。Console.WriteLine(new string('-', length));
  • Console.SetCursorPosition(posh+i, pov+i); 添加检查!

标签: c# loops for-loop cursor-position


【解决方案1】:

你需要增加X:

    public static void LineHorizontale(int x, int y, int length)
    {
        for (var i = 0; i < length; i++)
        {
            Console.SetCursorPosition(x + i, y);
            Console.Write("-");
        }
    }

对角线:

public static void LineDiaglonal(int x, int y, int length)
{
    for (var i = 0; i < length; i++)
    {
        Console.SetCursorPosition(x + i, y + i);
        Console.Write('\\');
    }
}

【讨论】:

  • 你对对角线有什么想法吗?
  • 是的。只需将“+ i”添加到 y。
【解决方案2】:

您需要将CursorPosition 设置为给定位置,然后需要绘制一条水平线。

喜欢,

public static void LineHorizontale(int x, int y, int length)
{
    //This will set your cursor position on x and y
    Console.SetCursorPosition(x, y);

    //This will draw '-' n times here n is length
    Console.WriteLine(new String('-', length));
}

如果要打印对角线,请使用\ 而不是- 并增加x 和y 位置。

类似的,

    public static void LineDiagonal(int x, int y, int length)
    {

        for(int i = 0; i < length; i++)
        {
            //This will set your cursor position on x and y
            Console.SetCursorPosition(x+i, y+i);

            //This will draw '\' n times here n is length
            Console.Write(@"\");

        }
    }

输出:

【讨论】:

  • 关于绘制对角线,你有什么想法吗?
猜你喜欢
  • 2021-07-18
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
相关资源
最近更新 更多