在 C 中向上增加 for 循环

2OL*_*OL1 0 c python loops

我希望用 C 中的 range() 函数模拟 Python for 循环。我想完成一项任务,每次循环的次数越来越多,直到达到给定变量的值,在这种情况下为 5(对于变量 h)。这是在 Python 中的:

x = 5
y = 0
while x > y:
    for i in range(y+1):
        print("@",end='') 
    print('')
    y+=1

Output: 
@
@@
@@@
@@@@
@@@@@
Run Code Online (Sandbox Code Playgroud)

我能够在 C 中完成相反的事情(执行次数减少),如下所示:

{
    int h = 5;
    
    while (h > 0)
    {
        for (int i = 0; i < h; i++)
        {
            printf("@");
        }
        printf("\n");
        h--;
    }
}

Output:
@@@@@
@@@@
@@@
@@
@
Run Code Online (Sandbox Code Playgroud)

当我在 C 中尝试顶级版本时,随着执行次数的增加,我遇到了不知道如何控制各种递增和递减变量的问题。

Mik*_*CAT 5

我建议你应该简单地思考:

  1. 增加@要打印的数量
  2. 使用循环打印该数量 @
#include <stdio.h>

int main(void)
{
    int h = 5;
    
    for (int c = 1; c <= h; c++) // the number of @ to print
    {
        for (int i = 0; i < c; i++)
        {
            printf("@");
        }
        printf("\n");
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是简单地以与 Python 版本相同的方式编写:

#include <stdio.h>

int main(void)
{
    int x = 5;
    int y = 0;

    while (x > y)
    {
        for (int i = 0; i < y+1; i++)
        {
            printf("@");
        }
        printf("\n");
        y += 1;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)