首页 > 解决方案 > 编程中的嵌套循环

问题描述

我将如何使用下面的代码显示内部 while 循环内的迭代次数。我想从外部循环的迭代次数中迭代内部循环。

printf("value: ");
scanf("%d", &x[0]);

/*printf("%d", x[0]);*/

 loop: while(a < x[0])
{
        while(b < x[0]) {
        b++;
}
printf("%d %d\n", a, b);
a++;
goto loop;
}
}

标签: c

解决方案


为什么你使用while循环?当您知道迭代次数时,请始终使用for循环。您知道迭代次数,因为您将其设置为输入。
所以你可以重写你的代码(基于你提供的稀有信息并且没有输入检查):

#include <stdio.h>

int main(void)
{
    int Input;

    printf("Enter a value: ");
    scanf("%d", &Input);

    for(int i = 0; i < Input; i++)
    {
        for(int j = 0; j <= Input; j++)
        {
            printf("%d %d\n", i, j);
        }
    }

    return 0;
}

或带有while循环(不良风格)

#include <stdio.h>

int main(void)
{
    int i = 0;
    int j = 0;
    int Input;

    printf("Enter a value: ");
    scanf("%d", &Input);

    while(i < Input)
    {
        j = 0;

        while(j <= Input)
        {
            printf("%d %d\n", i, j);

            j++;
        }

        i++;
    }

    return 0;
}

两种方式都会为您提供以下输出:

Enter a value: 2
0 0
0 1
0 2
1 0
1 1
1 2

推荐阅读