【问题标题】:Create random numbers for sums为总和创建随机数
【发布时间】:2016-06-06 10:58:15
【问题描述】:

我需要创建随机数,但标签中的数字不是随机的 2 是随机的,但所有总和都相同:

这是我的代码

int input = int.Parse(txt1.Text);
    if (input <= 6)
    {
        int Getal1 = 0;
        int Getal2 = 0;
        Random generator = new Random();
        for (int x = 0; x < 11; x++)
        {
            Getal1 = generator.Next(input) + 1;
            Getal2 = generator.Next(input) + 1;
            Getal1.ToString();
            Getal2.ToString();
        }
        //int Getal2 = generator.Next(input) + 1;
        //int Getal3 = generator.Next(input) + 1;
        //int Getal4 = generator.Next(input) + 1;
        //int Getal5 = generator.Next(input) + 1;
        //int Getal6 = generator.Next(input) + 1;
        //int Getal7 = generator.Next(input) + 1;
        //int Getal8 = generator.Next(input) + 1;
        //int Getal9 = generator.Next(input) + 1;
        //int Getal10 = generator.Next(input) + 1;


        lbl1.Text = Getal1.ToString();
        lbl2.Text = Getal2.ToString();
        lbl3.Text = Getal1.ToString();
        lbl4.Text = Getal2.ToString();
        lbl5.Text = Getal1.ToString();
        lbl6.Text = Getal2.ToString();
        lbl7.Text = Getal1.ToString();
        lbl8.Text = Getal2.ToString();
        lbl9.Text = Getal1.ToString();
        lbl10.Text = Getal2.ToString();

当我删除循环并撤消评论时它确实有效。但是代码太多了,我想我可以做得更小。

【问题讨论】:

  • 1) 你应该在 for 循环体之外声明变量“int Getal1”,因为现在这个变量只在 for 循环中可见 2)如果它没有给你任何其他效果,为什么你要使用 for 循环除了一次又一次地声明 Getal1 和 Getal2 值?

标签: c# asp.net


【解决方案1】:

您应该将Random generator = new Random(); 和所有变量声明移到循环之外。您还可以将所有标签放入一个数组中,因此您不必单独分配每个标签。此外,您已将标签的文本仅分配给最新的 Getal1, Getal2 值。这就是为什么只有所有其他对的值与第一对相同。

int input = int.Parse(txt1.Text);
if (input <= 6)
{
    Random generator = new Random();
    Label[] labels = new [] {
        lbl1,
        lbl2,
        lbl3,
        lbl4,
        lbl5,
        lbl6,
        lbl7,
        lbl8,
        lbl9,
        lbl10
    };

    for (int x = 0; x < labels.Length; x++)
    {
        labels[x].Text = (generator.Next(1, input)).ToString();
    }

    error.Text = "";
    pnl1.Visible = true;
}

默认的Random构造函数将随机种子初始化为一个基于当前时间的值。

【讨论】:

  • 但是 Getal1.ToString() 和 Getal2.ToString() 不起作用。它说它不存在
  • @KipVerslaafde 您还应该将变量声明移到循环之外。我已经更新了答案。
  • 无法在此范围内声明名为“Getal2”的本地或参数,因为该名称已在封闭的本地范围中用于定义获取此错误代码的本地或参数
  • generator.Next(1, input); - 随机从1 向上并包括input 更具可读性。
【解决方案2】:
    int input = int.Parse(txt1.Text);   
     Random r = new Random();
                    List<int> sums = new List<int>();
                    if(input<=8)
                    {

                        for (int i = 0; i <= 10; i++)
                        {
                            sums.Add( r.Next(input)+ r.Next(input));
                        }
 lbl1.Text = sums[0].ToString();
                    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 2011-05-30
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多