C#IndexOutOfRangeException

时间:2011-12-08 02:30:35

标签: c# arrays indexing geometry

在运行时,程序说索引超出范围,但我不知道为什么。

错误消息指出的行是

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;
        }
    }
}

提前谢谢

Adrian Collado

3 个答案:

答案 0 :(得分:3)

问题出在for循环的增量步骤中:i = i++。它应该是i++++i

i++递增i并返回其先前的值,然后再将其分配给i。因此,我实际上在循环的每次迭代中都得到相同的值,因此它永远不会大于radiusEnd,并且循环永远不会终止(直到计数器超出数组的上限并且你得到超出范围的异常)。

答案 1 :(得分:2)

我注意到在你进入循环之前没有初始化“counter”,尝试在之前将其初始化为0?

答案 2 :(得分:2)

我看到了奇怪的行为:i = i++

尝试将for (float i = radiusStart; i <= radiusEnd; i = i++)更改为仅使用i++而不是i = i++

即使它无法解决您的问题,也可以采用更好的形式。