c - 重构此 C 代码的最佳方法? CS50 - mario.c(更多)

标签 c for-loop cs50

所以我正在学习 cs50 类(class)并从 pset 1 中解决 mario.c 更多问题

我实际上用 3 个 for 循环解决了它,但我想用 2 个循环重构它,我想出了这段代码,为“height: 5”提供了以下解决方案

Result:
    #  #
   ##  ##
  ###  ###
 ####  ####
#####  #####

#include <stdio.h>

int main(void)
{
   
    int side = 5;
    int max = side + 2;

    for (int i = 1 ; i <= side ; i++)
    {
      int j = 1;
      while(j != max+1)
      {
        if(j <= side-i)
        {
        printf(" ");
        j++;
        }
        else if(j > side-i && j < side+1)
        {
        printf("#");
        j++;
        }
        else if(j == side+1)
        {
        printf("  ");
        j++;
        } 
        else 
        {
        printf("#");
        j++;
        }
      }
    max++;
    printf("\n");
    }
}

我想知道你们是否可以向我展示一个更优雅的解决方案,因为我认为这太......重复了。

另外,是否可以使用 switch case 来代替这么多 else if ?尝试这样做,但代码没有为 j 获取 bool 值:(

提前致谢! :)

最佳答案

如果您知道高度的上限,则可以在单个循环中完成。

喜欢:

int main(void) {
    char s[] = "#############################################";
    char f[32];

    int n = 5;  // height

    sprintf(f, "%%%ds  %%s", n);   // Create a format string like "%5s  %s"
    char* p = s + strlen(s) - 1;   // Let p point to the last char in s

    for(int i=0; i<n; i++)         // Loop n times
    {
        printf(f, p, p);
        printf("\n");
        p--;                       // Increase the number of # that p points to
    }
    return 0;
}

注意:如果您不知道高度的上限,您仍然可以使用此方法,但 s 必须动态分配。

关于c - 重构此 C 代码的最佳方法? CS50 - mario.c(更多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52134285/

相关文章:

C、用for循环初始化二维数组

c - 使用 readdir_r 读取目录

for-loop - 如何在 for 循环中进行可变借用?

c - 替换文本C语言中的字符串

JavaScript Promises - 在继续之前等待解决

python for循环遍历变量列表

c - 在 C 中 - 循环内递增的变量不保留值 CS50

c - 错误 : comparison between pointer and integer ('int' and 'string' (aka 'char *' ))

c - 将 *C.uint8_t 转换为 []uint8 是否安全?

C和MPI : function works differently with same data