繁体   English   中英

如何生成一个随机数...? 在 C# 中

[英]how to generate a random numbers...? in c#

我有一个二维数组按钮 [5,5] 全是蓝色...如何在数组中随机生成 5 个红色按钮...?

int Rows = 5;

int Cols = 5;

        Button[] buttons = new Button[Rows * Cols];
        int index = 0;
        for (int i = 0; i < Rows; i++)
        {
            for (int j = 0; j < Cols; j++)
            {
                Button b = new Button();
                b.Size = new Size(40, 55);
                b.Location = new Point(55 + j * 45, 55 + i * 55);
                b.BackColor = Color.Blue;
                buttons[index++] = b;
            }                
        }
        panel1.Controls.AddRange(buttons);

就这么简单

int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
    int idx = rnd.Next(Rows * Cols);
    if (buttons[idx].BackColor == Color.Blue)
    {
        buttons[idx].BackColor = Color.Red;
        cnt++;
    }
}

您将使用Random 类选择 0 到 24 之间的索引值,并使用该索引选择蓝色按钮之一,如果所选按钮具有蓝色背景色,请将其更改为红色

顺便说一句,这是有效的,因为您在这里没有真正的二维数组。
如果您的数组被声明为像这里这样的二维数组

Button[,] buttons = new Button[Rows, Cols];

那么每个循环需要两个随机值,一个用于行,一个用于列

int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
    int row = rnd.Next(Rows);
    int col = rnd.Next(Cols);

    if (buttons[row, col].BackColor == Color.Blue)
    {
        buttons[row, col].BackColor = Color.Red;
        cnt++;
    }
}

暂无
暂无

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

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