c - 使用C中的循环制作x的楼梯,但我不断得到正方形

标签 c loops for-loop nested

所以我需要做一个楼梯,但我的逻辑显然有问题。关于如何处理这个问题有什么建议吗?我最终只得到正方形。

#include <stdio.h>

int main()
{

    int a,b,z,y,p;
    char x;

    scanf("%i ", &a);
    printf("Number of stairs is: %i\n", a);
    printf("up: \n");

    for(b=0; b<a; b++) {
        for(z=1; a>=z; z++) {
            x='x';
            p=1;

            if ((p=z)) {
                printf("%c", x);
            }
            else {
                printf(" ");
            }               
            p++;
        }
        printf("\n");
    }
}

最佳答案

您的代码有很多缺陷,缺乏清晰度就是其中之一。尽管如此,你有一个正方形的原因是因为 p=z 始终为真(将 p 的值设置为 z 返回的值 z 并且在您的代码中始终为 1 或更高 - C 标准的真实值)。

这是一个可以工作的代码,大致基于您的示例:

#include <stdio.h>

int main() {    
    int numberSteps,currentStep,currentColumn;    
    scanf("%i", &numberSteps);
    printf("Number of stairs is: %i\n", numberSteps);
    printf("up: \n");    
    for(currentStep=0; currentStep<numberSteps; currentStep++) {
        for(currentColumn=0; currentStep>=currentColumn; currentColumn++) {            
            printf("x");            
        }
        printf("\n");
    }
}

请注意,我更改了变量名称,以便它们变得有意义,并且还删除了不必要的变量和不必要的测试 if ((p=z)) ,这些测试使您的代码变得困惑。

关于c - 使用C中的循环制作x的楼梯,但我不断得到正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32660340/

相关文章:

vba - 根据名称列表命名工作表

for-loop - 如何使用 openscad/for-loop 在立方体上打洞?

c - 给定一个指向结构中成员的指针,如何返回指向该结构的指针?

c - 这段从链表中删除节点的代码正确吗?

php - 填满的 $_FILES 不返回文件扩展名

php - 如何在没有函数的情况下在php中获取数组的所有组合

loops - 在 Julia 的 For 循环中单独计时不同的行?

c - 使用 fork() 执行 if/else if/else

c - 反调试技术的强度

C# 循环 - 中断与继续