【发布时间】: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