首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# IndexOutOfRangeException

C# IndexOutOfRangeException
EN

Stack Overflow用户
提问于 2011-12-08 10:30:35
回答 3查看 856关注 0票数 1

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

错误消息程序指出的行是

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

如果其中一个有错误,那么下一个(具有相同索引的)肯定也有错误。

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

代码如下:

代码语言:javascript
复制
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;
        }
    }
}

提前谢谢你

禤浩焯·科拉多

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-12-08 10:41:51

我在i = i++上看到了一些奇怪的行为

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

即使它不能解决你的问题,它也是更好的形式。

票数 2
EN

Stack Overflow用户

发布于 2011-12-08 10:46:23

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

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

票数 3
EN

Stack Overflow用户

发布于 2011-12-08 10:37:31

我注意到“计数器”在你进入你的循环之前没有被初始化,之前试着把它初始化为0吗?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8425410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档