【问题标题】:While loop wrong output given虽然给出了循环错误的输出
【发布时间】:2023-03-26 03:06:02
【问题描述】:

我有一个点列表List<Point> newcoor = new List<Point>(); 和特定坐标,它是点列表的中心。 int centerx, centery;

我想要做的是用 centerx 加 1,用 centery 减 1,直到它达到一个与列表中的 Point 匹配的组合。然后将该点存储在数组中。这是我的代码:

List<Point> newcoor = new List<Point>(); // list of points that where the tempx and tempy will be compared to.

//...

Point[] vector = new Point[4];

int x = 0;

while (x <= 3) 
{
    var tempx = centerx + 1; //add 1 to centerx
    var tempy = centerx - 1; //subtrat 1 to centery
    int y = 0;
    if (y < newcoor.Count() - 1 && newcoor[y].X == tempx && newcoor[y].Y == tempy) // compare if there is a Point in the List that is equal with the (tempx,tempy) coordinate
    {
        vector[x].X = tempx;// store the coordinates
        vector[x].Y = tempy;

    }
    break; // this is what I don't understand, I want to exit the loop immediately if the if-condition is true. And add 1 to x so the while loop will update.
}

尝试了新代码:

for (int y = 0; y < newcoor.Count() - 1; y++)
            {
                var tempx = centerx + 1;
                var tempy = centery - 1;
                for (int x = 0; x < newcoor.Count() - 1; x++)
                {
                    if (newcoor[y].X == tempx && newcoor[y].Y == tempy)
                    {
                        //vectorPoints.Add(new Point(tempx,tempy));
                        MessageBox.Show("success");

                    }
                }
            }

但是没有消息框成功显示,这意味着没有匹配。但必须有。

我只需要 4 个输出,这就是为什么我有条件 while (x

更新:

我的 centerx = 30 和 centery = 28

这是我的清单:

我想要做的是centerx加1centery减1

从原来的centerx= 30和centery= 28,应该是

(31,27) (32,26) (33,25) (34,24) (35,23)

【问题讨论】:

  • 只需将break 移动到if 块中:if (...) { ... break; }

标签: c# while-loop points


【解决方案1】:

不知道你在这里希望什么,但无论如何我可以发现几个问题;

首先,tempxtempy 在每个循环上将是相同的值,因为循环内没有任何东西操纵 centerxcentery

其次,循环将在第一次运行时退出,因为 break 语句不在 if {..} 块内。也许你的意思是;

if (y < newcoor.Count() - 1 && newcoor[y].X == tempx && newcoor[y].Y == tempy)
{
    vector[x].X = tempx;// store the coordinates
    vector[x].Y = tempy;

    break;  // <-- needs to be inside the if{..} block 
}

【讨论】:

  • 我想要做的是,将 +1 添加到 centerx 并减去 1 到 centery,直到该坐标与我的点列表中的点具有相同的值,即 newcoor。我已经更新了我的代码。请看一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2013-08-22
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多