首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CS50马里奥不用"CS50库“打印金字塔

CS50马里奥不用"CS50库“打印金字塔
EN

Code Review用户
提问于 2022-01-20 13:25:28
回答 1查看 91关注 0票数 2

我对编程很陌生,我只学习了C语言的基础知识。我决定解决哈佛CS50课程中的这个问题。请检查我的密码。

我们必须编写一个程序,从用户那里获取一个高度,并打印出这个高度的金字塔。

如果用户在提示下输入8,程序将如何工作:

代码语言:javascript
复制
    $ ./mario
Height: 8
       #  #
      ##  ##
     ###  ###
    ####  ####
   #####  #####
  ######  ######
 #######  #######
########  ########

我的代码:

代码语言:javascript
复制
#include <stdio.h>
void pattern(int n, int temp); // function prototype
int main()
{
    int height, same_as; // same_as is just a temporary variable
    printf("Enter the height \n");
    while (1)
    {
        scanf("%d", &height);
        if (height >= 1 && height <= 8) // if height is between 1 and 8
            break;
        else
            printf("Height = %d\n", height);
    }
    same_as = height;
    printf("Height = %d\n", height);
    pattern(height, same_as);
    return 0;
}

// definition of the function
void pattern(int n, int temp)
{
    int i; // i is the counter

    // printing the first line
    if (n == 1)
    {
        for (i = 0; i != 2 * temp + 1; i++)
        {
            if (i == temp - 1 || i == temp + 1)
            {
                printf("#");
            }
            else if (i == temp)
            {
                printf("  ");
            }

            else if (i > temp + 1)
                break;

            else
                printf(" ");
        }
        printf("\n");

        return;
    }

    else
    {
        pattern(n - 1, temp);

        // for loop to print each line
        for (i = 0; i != 2 * temp + 1; i++)
        {
            // all the places where we print # in the same  line
            if (i >= temp - n && i <= temp + n && i != temp) // very important
            {
                printf("#");
            }

            else if (i == temp)
            {
                printf("  ");
            }

            else if (i > temp + n)
                break;
            else
                printf(" ");
        }
        printf("\n");
    }
}
EN

回答 1

Code Review用户

回答已采纳

发布于 2022-01-20 14:38:32

当您使用scanf()时,在使用您要分配给它的任何值之前,检查它的返回值非常重要。

例如,尝试输入一个非数字:它将不断循环,重新尝试解析无效的输入。

如果输入不能被解析,那么最好放弃,当然在C职业生涯的这个阶段(非常健壮的输入处理是一个高级主题)。

代码语言:javascript
复制
    if (scanf("%d", &height) != 1) {
        fputs("Sorry, I didn't understand you.\n", stderr);
        return EXIT_FAILURE;
    }

注意:我们需要包含<stdlib.h>来定义返回值。

额外的变量same_as是不必要的:

代码语言:javascript
复制
pattern(height, height);

还不清楚temp参数的作用是什么:

空模式( int n,int temp)

它真的需要一个更好的名字。

(部分回顾-我可能会有时间回到这里)

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/273181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档