2011-12-08 37 views
1

在運行時程序說索引超出範圍,但我不知道爲什麼。C#IndexOutOfRangeException

該錯誤信使指出該生產線是

Points[counter + ((int)(radius * 100))].X = i;

如果一個有錯誤,下一個(具有相同的指數)也必須具有誤差。

Points[counter + ((int)(radius * 100))].Y = (Points[counter].Y * -1);

下面是代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication5 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Circle circle = new Circle(new Point2D(30F, 30F), 10F); 
      foreach (Point2D point in circle.Points) 
      { 
       Console.Write(point.X + " = X\n" + point.Y + " = Y"); 
       Console.ReadKey(); 
      } 
     } 
    } 

    public struct Point2D 
    { 
     public float X; 
     public float Y; 

     public Point2D(float x, float y) 
     { 
      this.X = x; 
      this.Y = y; 
     } 
    } 

    class Circle 
    { 
     public Point2D[] Points; 
     float h, k; 
     float radiusStart, radiusEnd; 
     int counter; 

     public Circle(Point2D location, float radius) 
     { 
      Points = new Point2D[(int)(radius * 201)]; 
      h = location.X; 
      k = location.Y; 
      radiusStart = h - radius; 
      radiusEnd = h + radius; 

      for (float i = radiusStart; i <= radiusEnd; i++) 
      { 
       Points[counter].X = i; 
       Points[counter].Y = (float)(Math.Sqrt((radius * radius) - ((i - h) * (i - h))) + k); 
       Points[counter + ((int)(radius * 100))].X = i; 
       Points[counter + ((int)(radius * 100))].Y = (Points[counter].Y * -1); 
       counter++; 
      } 

      counter = 0; 
     } 
    } 
} 

預先感謝您

阿德里安·科利亞

+0

您是否嘗試過調試該值? –

+2

你應該再次考慮一下這段代碼。 – Jon

+0

循環中的計數器值在哪裏?您已將計數器分配爲整數,但沒有任何值。 – Hoque

回答

2

我見過的怪異行爲有:i = i++

嘗試改變for (float i = radiusStart; i <= radiusEnd; i = i++)只使用i++代替i = i++

即使它沒有解決你的問題,它的形式也好多了。

+0

我必須在意外鍵入i =之前..感謝您注意! –

2

我注意到, 「反」 是不是你在你的循環得到初始化之前,嘗試之前將其初始化爲0?

+1

'counter'是CLR保證爲零的成員。 –

+0

馬修是對的。還是很好的做法,但這不是問題。 –

3

問題出在for循環的增量步驟中:i = i++。它應該是i++++i

i++遞增i並返回其先前的值,然後再將其分配給i。因此,我實際上在循環的每次迭代中都會得到相同的值,所以它永遠不會比radiusEnd大,並且循環永遠不會終止(直到計數器超出數組的上限並且出現超出範圍的異常)。

相關問題