c - 如何优化公式?

标签 c loops nested-loops

这里的代码完全可以完成它的工作,只是我不喜欢的一行。我想知道是否还有更优雅的解决方案?

void spaces(void)
{
    int rows = 5;
    int i, b, c, d;
    char ch;
    printf("Please enter capital letter \'A\'\n");
    scanf("%c", &ch);

    for (i = 1; i <= rows; i++)
    {
        for (b = rows; i < b; b--)
            printf(" ");
        for (c = 0, ch = 'A'; c < i; c++, ch++)
            printf("%c", ch);
        for (d = 1, ch = 'A'; d < c; d++, ch--)
                         /*┏━━━━━━━━━━━━━━━━━━━┓*/
            printf("%c", /*┃*/ (ch + b) - 2) /*┃*/; //This line here!!!
                         /*┗━━━━━━━━━━━━━━━━━━━┛*/

        printf("\n");
    }

    return;
}


//输出
The code draws the x-mas tree

最佳答案

   for (c = 0, ch = 'A'; c < i; c++, ch++)
       printf("%c", ch);
   for (d = 1, ch = 'A'; d < c; d++, ch--)
                    /*┏━━━━━━━━━━━━━━━━━━━┓*/
       printf("%c", /*┃*/ (ch + b) - 2) /*┃*/; //This line here!!!
                    /*┗━━━━━━━━━━━━━━━━━━━┛*/





替换第二个控制循环以使用ch

for (; ch > 'A'; ) putchar(--ch);


我想要一会儿

while (ch > 'A') putchar(--ch);

关于c - 如何优化公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59598931/

相关文章:

c - 指针大小相同吗?

c# - 遍历模型属性并在代码文件中获取值

带有嵌套循环的 Javascript 嵌套数组

c++ - 两个 for 嵌套循环的区别。(C++)

python - 使用用户输入打破嵌套循环

c - Turbo C++ 调试问题

c - C 中接收函数调用

c - GCC-4.3.2 中提供的标准算法

javascript - Interval/setTimeout 起始点

php - Mysql仅在之前插入行时才更新