我正在进行一项作业,其中我必须逐行填写一个二维数组。如果该行的索引值为,甚至(0,2,4等),则该行必须从填充,从右到左。如果该行的索引值为不均匀(1,3,5等...),那么它必须从左至右填充。我应该在我的if语句中填入什么条件才能以这种方式填充行?如何确定数组索引是否均匀?
谢谢!
我正在进行一项作业,其中我必须逐行填写一个二维数组。如果该行的索引值为,甚至(0,2,4等),则该行必须从填充,从右到左。如果该行的索引值为不均匀(1,3,5等...),那么它必须从左至右填充。我应该在我的if语句中填入什么条件才能以这种方式填充行?如何确定数组索引是否均匀?
谢谢!
您需要使用模或余数操作。假设i是不均匀的数字,因此i%2将评估为。对于偶数i%2将导致。正如评论中指出的那样,使用条件 if (row_index % 2 == 0) {*do right to left thing*} else {do right to left thing}
。
作为用户与奇怪的名字,我不知道如何引用(对不起,请随时编辑你的名字在这里)指出,我%2 == 0应该解决这个问题。
%(模)运算符返回整数除法的余数,因此,如果行数为偶数则可以除以2,并具有没有余数(I%2 == 0)
int[][] toBeFilled = new int[width][height];
for(int i=0;i<width;i++) {
if(i%2==0)
//Fill toBeFilled[i] from Right to Left
else
//Fill toBeFilled[i] from from Left to Right
}
以下是可能有所帮助的代码示例。请注意,这是C#(我现在没有坐在Java编译器前面),所以有一些很小的语法差异,但它应该仍然非常易读。
private static int[][] BuildArrays()
{
Random random = new Random();
// Whatever size you want
int[][] array = new int[random.Next(1, 100)][];
for (int i = 0; i < array.Length; i++)
{
// Make an array of whatever size you want
array[i] = new int[random.Next(1, 50)];
// % is the modulo operator
// Basically, this means "remainder when the index is divided by 2"
// By definition, even numbers are evenly divisible by 2 and odd numbers aren't
if (i % 2 == 0)
{
// Even - we fill right to left
for (int j = array[i].Length - 1; j >= 0; j--)
{
// Enter whatever you want
array[i][j] = random.Next();
}
}
else
{
// Odd - we fill left to right
for (int j = 0; j < array[i].Length; j++)
{
array[i][j] = random.Next();
}
}
}
return array;
}
i%2 == 0会检查 –
或者if(index&1){/ *它很奇怪* /}' –