【问题标题】:Works during debug, fails when run?在调试期间工作,在运行时失败?
【发布时间】:2014-01-21 19:14:07
【问题描述】:

对于一些课程,我需要通过蛮力生成一个普通的幻方,这是代码的一部分。供参考;我不允许使用除常用的类以外的任何类。 (我可能在 Math.Pow 上碰运气)

我有以下方法来生成大小为 NxN 的二维:

    static int[,] GenerateSquare(int n)
    {
        int[,] sqarray = new int[n,n];
        int[] rndarray = new int[n];

        //puts completely random integers from 1 to n^2 in all elements of the square array (sqarray)
        for (int i = 0; i < n; i++)
        {
            rndarray = FullRndArray(n);

            for (int j = 0; j < n; j++)
            {
                sqarray[i, j] = rndarray[j];
            }
        }

        return sqarray;
    }

FullRndArray() 方法如下:

static int[] FullRndArray(int n)
    {
        //creates an array of size n and fills with random intigers between 1 and n^2
        int[] rndarray = new int[n];
        Random rnd = new Random();

        int ntothe2 = Convert.ToInt32(Math.Pow(n, 2));

        for (int i = 0; i < n; i++)
            rndarray[i] = rnd.Next(1, ntothe2 + 1);

        return rndarray;
    }

问题是当我运行这段代码时,每一行的内容是随机的,但是正方形的每一行都和上一行一样(即1-1、1-2、1-3与2-1、2-2、2-3,分别与 3-1、3-2、3-3 相同)。然而,当我逐行通过调试器时,我最终会在每个空间中得到一组完全随机的数字。谁能给我解释一下这个错误吗?

【问题讨论】:

  • 您可以通过使用n * n 来消除Math.Pow。一般来说,你可以使用(int)而不是Convert.Int32,除非你想要四舍五入。

标签: c# arrays debugging random 2d


【解决方案1】:

这是罪魁祸首:

Random rnd = new Random();

随机数是从一个种子开始生成的:相同的种子意味着相同的非随机数序列Random 使用当前时间作为种子,因此当您运行代码时,它运行得非常快,以至于您创建了两个具有相同种子的 Randoms,然后生成两个相同的行。另一方面,当您进行调试时,您需要等待足够的时间,一切都会按预期进行。
解决方案是创建Random 的实例,静态或GenerateSquare 的开头,并在整个过程中使用该实例。

【讨论】:

  • 非常感谢您的解释! :) 现在或多或少可以正常工作
【解决方案2】:

我的行为与您描述的完全相同。

这似乎有效:

static int[,] GenerateSquare(int n)
{
    int[,] sqarray = new int[n, n];
    int[] rndarray = new int[n];

    Random rnd = new Random();
    //puts completely random integers from 1 to n^2 in all elements of the square array (sqarray)
    for (int i = 0; i < n; i++)
    {
        rndarray = FullRndArray(n, rnd);
        for (int j = 0; j < n; j++)
        {
            sqarray[i, j] = rndarray[j];
        }
    }

    return sqarray;
}
static int[] FullRndArray(int n, Random rnd)
{
    //creates an array of size n and fills with random intigers between 1 and n^2
    int[] rndarray = new int[n];

    int ntothe2 = Convert.ToInt32(Math.Pow(n, 2));

    for (int i = 0; i < n; i++)
        rndarray[i] = rnd.Next(1, ntothe2 + 1);

    return rndarray;
}

我知道我们必须在同一实例上使用 Random.Next() 方法才能“真正”随机(如 BlackBear 回答中所述)。

它可能在调试期间起作用,因为您在步骤之间产生了时间间隔。

【讨论】:

  • 感谢您的示例修复:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
相关资源
最近更新 更多