超出范围的二维数组
问题描述:
Techies-- 此代码适用于具有单个通道或具有均匀分割的情况。它差不多的作品,当我有余数...因为它会创建下一个通道,它会拉入物品,但然后超出范围。这些线是麻烦的心脏:超出范围的二维数组
items_per_batch = batchcount/(int)channels; //
subsets = batch.Split(items_per_batch);
items_per_batch真的是用来给分割扩展通用一些关于有多少项目由分裂的想法。如果它看到一个余数,它只是创建另一个子集数组。我真正需要做的是跟踪项目的长度。我试过了:
int idx2 = subset.GetLength(1)
在一个点上,但是使用该值的forloop也超出了范围。任何人有任何建议?
static void channelassign()
{
int THRESHOLD = 2;
string[] batch = new string[]
{ "item1", "item2", "item3", "item4","item5","item6","item7" };
int batchcount = batch.Count();
int items_per_batch;
string[][] subsets;
int idx1;
int idx2;
if (THRESHOLD != 0) //avoid accidental division by 0.
{
float channels = batchcount/THRESHOLD;
if (channels < 1)
{
channels = 1; // only 1 channel is needed
items_per_batch = batchcount; // process all items
idx1 = 1; // fix value to a single channel
idx2 = (batchcount - 1); // true start of array is 0
subsets = batch.Split(batchcount); //splits correctly
}
else
{
// decide how many items will be included per batch
channels = (int)Math.Round(channels,
MidpointRounding.ToEven); //determines channel number
items_per_batch = batchcount/(int)channels; //
subsets = batch.Split(items_per_batch);
idx1 = subsets.GetLength(0); // gets channel# assigned by split
// idx2 = subsets.GetLength(1); // gets items back from splits
}
//distribute contents of batch amongst channels
for (int channel = 0; channel < idx1; channel++)
{
for (int i = 0; i < items_per_batch; i++)
{
Console.WriteLine(" Channel:" + channel.ToString() + "
ItemName: {0} ", subsets[channel][i]);
}
}
}
else
{
Console.WriteLine("Threshold value set to zero. This
is an invalid value. Please set THRESHOLD.");
}
答
该科int
s的执行
float channels = batchcount/THRESHOLD;
,所以你float channels
总是有一个整数值,等于
floor(batchcount/THRESHOLD)
但是,这不是你的问题的原因,那是
for (int channel = 0; channel < idx1; channel++)
{
for (int i = 0; i < items_per_batch; i++)
如果batchcount
不是channels
的倍数,则某些频道的项数少于items_per_batch
。因此内循环尝试访问不存在的subsets[channel][i]
。
我在代码中看到不少于*三个不同的变量命名约定。说实话有点儿精神分裂症。 – 2012-07-31 18:03:09
不知道正在使用Split扩展方法,或者您为其提供源代码;你还没有提供任何东西给任何人去... – 2012-07-31 18:07:59