首页 > 解决方案 > 如何使用循环显示带有模式的整数?

问题描述

我正在尝试显示整数

1111
222
33
4

使用循环,但我不知道我的代码有什么问题,我是 c 编程新手,感谢您的帮助:D 这是我的代码:

#include <stdio.h>
int main()
{
    int a, b;

    for (int a=4; a<=1; a--) 
    {
        for (int b=1; b<=a; b++) {
        printf("%d", b);
        }
    } 
    printf("\n");
}

标签: cloopsfor-loop

解决方案


怎么了:

#include <stdio.h>
int main()
{
    int a, b;

    for (int a=4; a<=1; a--) /* a<=1 is false when a=4 */
    {
        for (int b=1; b<=a; b++) {
        printf("%d", b); /* what is printed depends on b while it shouldn't */
        }
    } 
    printf("\n"); /* this is in wrong place */
}

固定代码:

#include <stdio.h>
int main()
{
    int a, b;

    for (int a=4; a>=1; a--)
    {
        for (int b=1; b<=a; b++) {
            printf("%d", 1 + (4 - a));
        }
        printf("\n");
    }
}

推荐阅读