【问题标题】:For loop doesn't work but while loop doesFor 循环不起作用,但 while 循环起作用
【发布时间】:2017-11-02 12:04:12
【问题描述】:

我创建了一个在特殊区域周围创建边框的函数(这些信息存储在下面的结构表中):

typedef struct s_letter_stock
{
    int element_nb;
    int width;
    int height;
    t_pos square_p1;
    t_pos square_p2;
} g_letter_stock;
//those values are for the example
g_letter_stock letter_infos[] = {{ 0, 0, 0, {0, 0}, {0, 0} },
                                 { 0, 0, 0, {0, 0}, {0, 0} }};

我发现了一个疯狂的错误:下面函数中的 for loop 第一次工作得很好,但是如果在循环结束时有一个中断,它就会停止(当我打印 nb_elem 它有正确的值)。所以基本上我不知道为什么forwhile(在cmets 中)工作时停止。您对这种奇怪的行为有任何想法吗?我没有想法。

void create_borders(char **map, int nb_elem)
{
    printf("nb_elem : %d\n", nb_elem);
    for (int i = 0 ; i < nb_elem ; i++) //THIS dosnt work and stop once i = 1
        // int i = 0;                    //ALL the commentes are part of the other
        // int j = 0;                    //solution that i found which is working
        // while (j < nb_elem)
    {
        int newx = -1;
        int newy = -1;
        while (newx <= letter_infos[i].width + 1 ||
               newy <= letter_infos[i].height + 1)
        {
            if (letter_infos[i].square_p1.y - 1 >= 0 &&
                newx <= letter_infos[i].width + 1)
                map[letter_infos[i].square_p1.y - 1][letter_infos[i].square_p1.x + newx] = '@';
            if (letter_infos[i].square_p1.x - 1 >= 0 &&
                newy <= letter_infos[i].height + 1)
                    map[letter_infos[i].square_p1.y +
                        newy][letter_infos[i].square_p1.x - 1] = '@';
            if (letter_infos[i].square_p2.y + 1 < strlen (map[0]) &&
                newx <= letter_infos[i].width + 1)
                map[letter_infos[i].square_p2.y + 1][letter_infos[i].square_p2.x - newx] = '@';
            if (letter_infos[i].square_p2.x + 1 < my_tablen (map) &&
                newy <= letter_infos[i].height + 1)
                map[letter_infos[i].square_p2.y - newy][letter_infos[i].square_p2.x + 1] = '@';
            newx++;
            newy++;
        }
        printf ("i = %d\n", i);
        i++;
        //j++;
    }
}

【问题讨论】:

  • 最后的i++是否也属于while-variant,你忘了注释掉?
  • 尝试删除底部j++附近的i++
  • 该死的人......这就是它不起作用的原因......我不知道为什么我首先把它放在那里。好吧,我觉得自己很愚蠢,但至少我有我的答案,谢谢。
  • 如果您还有其他问题,请不要将其编辑到您的问题中,而是在单独的问题帖子中提出,但您应该能够通过 @ 找出这两个问题的答案987654321@ 和/或debugging
  • @Dukeling 好的,谢谢,我想知道如何编辑问题,因为目前我还没有看到有人这样做

标签: c algorithm loops


【解决方案1】:

我看到每个循环有 2 次执行时间 i++(在 for (int i = 0 ; i &lt; nb_elem ; i++) 和循环结束时)

【讨论】:

    【解决方案2】:

    你需要删除语句:

    i++;
    

    for 循环的底部,因为您已经在for 条件的第三部分增加了i

    【讨论】:

      猜你喜欢
      • 2020-03-30
      • 2014-10-15
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 2016-01-18
      相关资源
      最近更新 更多