c# - 索引越界问题

标签 c# arrays

我依次有以下两个 for 循环。当我单独运行时,第一个 for 循环起作用,这很奇怪。但是当我单独运行第二个循环时,我得到了一个索引超出范围的异常错误。有人可以帮我检查错误是什么吗?非常感谢!

for (i = NiPricePointer; i < 551; i++)  
   {
      tempUpper = tempUpper + NiPriceCounter[i];
      if (tempUpper >= (NiPriceRounds * 0.3))
      {
          chart3.Series["Upper 30%"].Points.AddXY(k * 500, ((i - 1) * 0.1 + 5));
          break;
      }
 }

for (i = NiPricePointer; i>0; i--) //This loop always gives me out of range problems.
 {
      tempLower = tempLower + NiPriceCounter[i];
      if (tempLower >= (NiPriceRounds * 0.3))
      {
          chart3.Series["Lower 30%"].Points.AddXY(k * 500, ((i - 1) * 0.1 + 5));
          break;
       }
 }

数组的初始化:

int[] NiPriceCounter = new int[551];

非常感谢!

最佳答案

我想,NiPricePointer 只是大于 550。您的两个循环都应包含两个边界作为检查:

for (i = NiPricePointer; i < 551 && i >=0; i++)  

for (i = NiPricePointer; i < 551 && i >=0 ; i--)

关于c# - 索引越界问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5156558/

相关文章:

arrays - 如何在 Swift 中转换 Int 数组中的字符串(数字)

java - 将单词的字符添加到 JButtons 中

javascript - 与 Node 异步不是更好吗

c - 整数数组的最后一个值覆盖所有其他值

c# - 第三方引用的dll没有被复制构建出来

c# - 将现有的 C# 和 ASP.NET Web 表单站点传输到 Bootstrap

c# - 编译器错误消息 : CS0029: Cannot implicitly convert type 'int' to 'string'

C# 与多线程共享锁

c# - HTML 中的 ASP.NET C# 函数

c - sizeof(数组)/sizeof(int)