超出范围的双维数组

时间:2012-07-31 17:58:55

标签: c# arrays

Techies-- 当我有一个频道或我有一个偶数分割时,此代码有效。当我有一个余数时,几乎工作......因为它将创建下一个通道并且它将拉入该项目,但随后超出范围。这些线是麻烦的核心:

    items_per_batch = batchcount / (int)channels; //
    subsets = batch.Split(items_per_batch); 

items_per_batch实际上用于为Split扩展提供有关要拆分的项目的一般数字的概念。如果它看到一个余数,它只是创建另一个子集数组。我真正需要做的是跟踪物品的长度。我试过了:

    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.");
        }

1 个答案:

答案 0 :(得分:2)

分部

float channels = batchcount / THRESHOLD;

int s上执行,因此您的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]