gpt4 book ai didi

C# IndexOutOfRangeException 异常

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:22 29 4
gpt4 key购买 nike

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

错误信息指出的行是

点[计数器 + ((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;
}
}
}

提前致谢

阿德里安科拉多

最佳答案

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

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

关于C# IndexOutOfRangeException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425410/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com