我正在开发一个C#程序,它必须在一维数组上复制随机10 * 12 2D数组的元素。一切似乎都很好。但是,2D阵列的某些元素(最后18个)不会复制到1D阵列。
以下是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace James_Archbold_A1
{
class Program
{
static void Main(string[] args)
{
int row = 10;
int column = 12;
int[,] twoDArray = new int[row, column];
int[] oneDArray = new int[row*column];
FillTwoDimArray(twoDArray);
DisplayTwoDimArray(twoDArray);
StoreValues(twoDArray, oneDArray);
DisplayOneDimArray(oneDArray);
Console.ReadLine();
}
static void FillTwoDimArray(int[,] table)
{
int min = 0;
int max = 100;
int rndNumber;
Random rnd = new Random();
for (int row = 0; row < table.GetLength(0); row++) //use GetLength(0) to get the size of the row
{
for (int col = 0; col < table.GetLength(1); col++) //use GetLength(1) to get the size of the column
{
rndNumber = rnd.Next(min,max);
table[row, col] = rndNumber;
}
}
}
static void DisplayTwoDimArray(int[,] table)
{
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.Write("{0}\t", table[row, col]);
}
}
Console.WriteLine();
}
static void StoreValues(int[,] twoDArray, int[] oneDArray)
{
int rowSize = twoDArray.GetLength(0);
int colSize = twoDArray.GetLength(1);
for (int row = 0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
{
int element;
element = twoDArray[row, col];
oneDArray[row * rowSize + col] = element;
}
}
}
static void DisplayOneDimArray(int[] oneDArray)
{
for (int i = 0; i < oneDArray.GetLength(0); i++ )
{
Console.Write("{0}\t", oneDArray[i] );
}
Console.WriteLine();
}
}
}
答案 0 :(得分:4)
如果您有2x5阵列,则rowSize
为2,colSize
为5.然后您的循环将值设置到[row * rowSize + col]
的数组中。其中的前几个值将是:
0*2+0 = 0
0*2+1 = 1
0*2+2 = 2
0*2+3 = 3
0*2+4 = 4
1*2+0 = 2
1*2+1 = 3
1*2+2 = 4
1*2+3 = 5
因此,您循环使用相同的值,多次设置它们,也不设置数组中的最后一个值。如果你有多行而不是列,我想你会得到一个超出范围的异常?
如果您将row * rowSize + col
更改为正确的映射row * colSize + col
,则应该有效。
答案 1 :(得分:0)
尝试将以下代码复制到1D:
void StoreValues(int[,] twoDArray, int[] oneDArray)
{
int rowSize = twoDArray.GetLength(0);
int colSize = twoDArray.GetLength(1);
var total=rowSize*colSize;//TOTAL ITEMS IN 1D ARRAY
for (int row = 0, d=0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
{
//STORE AT POSITION d
oneDArray[d++] = twoDArray[row, col];
}
}
}
使用row * rowSize + col
会导致问题,如this answer中所述。