我正在开发一个 C# 程序,该程序必须将随机 10*12 二维数组的元素复制到一维数组上。一切似乎都运行良好。但是,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();
}
}
}