繁体   English   中英

遇到怪异的循环行为

[英]Came across weird loop behaviour

我有点傻,但是我找不到解决方案,所以我在这里问。 我的代码的目的是将2D数组4x4填充为0-255之间的随机数,并将其呈现给面板。 问题是,我有两个函数:RenderArray()和WriteToTextbox()。 仅当它们之一从数组读取为array [y,x]而不是array [x,y]时,它们都从数组返回相同的值。 我觉得这种行为很怪异,我不能简单地想到原因。 这是代码:

    private bool newRequest;
    private bool hasGenerated;
    private int[,] array = new int[4, 4];
    private static Random random = new Random();

    private void btnRandom_Click(object sender, EventArgs e)
    {
        if (!HasGenerated)
        {
            HasGenerated = true;
        }

        NewRequest = true;
        pnlRandom.Refresh();
    }

    public bool NewRequest
    {
        get { return newRequest; }
        set { newRequest = value; }
    }

    public bool HasGenerated
    {
        get { return hasGenerated; }
        set { hasGenerated = value; }
    }

    public static Random GetRandom
    {
        get { return random; }
    }

    private void pnlRandom_Paint(object sender, PaintEventArgs e)
    {
        if (!HasGenerated)
        {
            return;
        }

        if (NewRequest)
        {
            for (int x = 0; x < 4; x++)
            {
                for (int y = 0; y < 4; y++)
                {
                    array[x, y] = GetRandom.Next(0, 256);
                }
            }

            NewRequest = false;
        }

        RenderArray(e);
        WriteToTextbox();
    }

    private void RenderArray(PaintEventArgs e)
    {
        Graphics g = e.Graphics;

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {
                //int color = array[y, x]; If I write it like that
                //they will return same values.
                int color = array[x, y];
                SolidBrush brush = new SolidBrush(Color.FromArgb(color, color, color));
                Rectangle rect = new Rectangle(x * 64, y * 64, 64, 64);

                g.FillRectangle(brush, rect);
            }
        }
    }

    private void WriteToTextbox()
    {
        txtRandom.Clear();

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {
                int length = array[x, y].ToString().Length;
                txtRandom.Text += array[x, y].ToString().PadLeft(3 * 4 - length + 3 * 4 % 3);
            }

            txtRandom.Text += "\r\n";
        }
    }

您正在以错误的顺序迭代循环。

绘制数组时,先循环遍历x还是y都没有关系。 无论哪种方式,每个单元格都将在传递给FillRectangle()的坐标处绘制。

将数组打印为字符串时,请按照迭代顺序写入字符。
通过循环遍历x ,然后遍历y ,您遍历了数组中的每一x ),然后循环遍历该列( y )垂直向下放置单元格。
因此,您要打印转置的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM