c - 在 C 中打印数字钻石

标签 c

int print_pattern(){
    int x;
    int y;
    int i;
    //for loop for the bottom and the top, 0 is the top and 1 is the bottom while it stops at anything above 2.
    for (i = 0; i<2;i++){
        //loop to the current number
        for (x=1;x<=input;x+=2){
            // top or bottom, this is the top because i had made the top of the diamond the 0
            // therefore this makes my diamond print the top of the function.
            if ( i == 0){
                //starts for the top of the diamond. and counts the spaces.
                for (y=1; y<=input-x; y++){
                    printf(" ");
                }
                //starts the printing of the diamond.
                for (y=1; y<2*x;y++){
                    printf("%d ", y);
                }
            }
            //bottom of the diamond, which is from the 1. For this spot it take in the one from the for loop to
            // this if statement.
            if (i==1){
                //counting spaces again
                for(y = 1; y<=x; y++){
                    printf(" ");
                }
                //printing again but this is the bottom of the pyramid. #really need to comment more
                for(y = 1; y<(input-x)*2;y++){
                    printf("%d ", y);
                }
            }
            //next line starts when printing out the numbers in the output.
            printf("\n");
        }
    }
}

输出应该看起来像每行以奇数结尾的数字菱形。但它会超过输入 +2 数字,然后也不会打印最后一行。哪个应该有一个。

                       1                     1
                     1 2 3                 1 2 3 4 5
                   1 2 3 4 5             1 2 3 4 5 6 7 8 9
                     1 2 3                1 2 3 4 5 6 7
                       1                    1 2 3

左边是预期的,右边是我目前输入 5 时得到的结果。

最佳答案

因为你已经增加了x通过上部的 2,您不需要让打印循环运行到 y<2*x .它可能应该运行到 x .

下部的打印循环受到 y<(input-x)*2 的影响。应该是 y<input-x*2 (你想每次少打印2)。

通常我会尝试以更通俗易懂的方式命名变量,例如 printStartPosition , maxNumToPrint , 像这样的东西。这使得理解程序变得更加容易。

作为增强,这两个代码块取决于 i x 内的值循环在结构上非常相似。人们可以尝试利用它并将它们都折叠成一个函数,该函数获取一个 bool 参数,如“升序”,递增y。为真时递减,为假时递减。这是否提高或阻碍了可读性将不得不被看到。

此外,如果可能,请将变量保留在本地。

关于c - 在 C 中打印数字钻石,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427594/

相关文章:

c++ - 在 C++ 中使用 extern 时出错

c - ATMEGA328p 将模拟值转换为电压

c++ - 测量计算几何算法的运行时间

计算简单排序程序中的比较和交换

c - C 代码有问题

python - Python3中sys.stderr是 block 设备还是字符设备?

c - C中的rs232字符串比较

c - 在不违反标准的情况下使用指向结构的指针对数组进行别名

c - 将局部变量的指针返回到 main() 函数

c - 在C程序中设置执行外部程序的路径