C# IndexOutOfRangeException

本文关键字:IndexOutOfRangeException | 更新日期: 2023-09-27 18:17:02

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

错误消息指出的行是

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

C# IndexOutOfRangeException

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

i++增加i并返回它之前的值,然后再次赋值给i。因此,在循环的每次迭代中,i实际上都以相同的值结束,因此它永远不会大于radiusEnd,并且循环永远不会终止(直到counter超过数组的上界并得到超出范围的异常)。

我见过:i = i++的奇怪行为

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

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