首页 > 解决方案 > 如何在C中删除最顶部的空格

问题描述

#include <cs50.h>
#include <stdio.h>

//Prototypes.
void print_hashes(int n);
void print_spaces(int n);

//Main function.
int main(void)
{
    //Recieves,checks and saves user input. Prompts to enter information again if invalid.
    int height = -1;
    while (height < 1 || height > 8)
    {
        height = get_int("Height: ");
    }

    //Outputs graphic to the screen with the use of logic with functions.
    for (int h = 0; h <= height; h++)
    {
        print_spaces(height - h);
        print_hashes(h);
        printf("  ");
        print_hashes(h);
        printf("\n");
    }
}


//Function for printing hashes to the screen.
void print_hashes(int n)
{
    for (int c = 0; c < n; c++)
    {
        printf("#");
    }
}

//Function for printing spaces to the screen so the hashes will be in the right spot.
void print_spaces(int n)
{
    for (int c = 0; c < n; c++)
    {
        printf(" ");
    }
}

输出:

Height: 8
          
       #  #
      ##  ##
     ###  ###
    ####  ####
   #####  #####
  ######  ######
 #######  #######
########  ########

你看到在顶部,在高度的正下方,金字塔图形和高度之间有一个空间:8 我不想要那个。另外,我是一个大型 C 初学者,没有复杂的库和主题,请只使用普通的基本语法。

到目前为止我已经尝试过

if (h > 0)
        {
        printf("\n");
        }

在这样的主for循环中

#include <cs50.h>
#include <stdio.h>

//Prototypes.
void print_hashes(int n);
void print_spaces(int n);

//Main function.
int main(void)
{
    //Recieves,checks and saves user input. Prompts to enter information again if invalid.
    int height = -1;
    while (height < 1 || height > 8)
    {
        height = get_int("Height: ");
    }

    //Outputs graphic to the screen with the use of logic with functions.
    for (int h = 0; h <= height; h++)
    {
        print_spaces(height - h);
        print_hashes(h);
        printf("  ");
        print_hashes(h);
        if (h > 0)
        {
        printf("\n");
        }
    }
}


//Function for printing hashes to the screen.
void print_hashes(int n)
{
    for (int c = 0; c < n; c++)
    {
        printf("#");
    }
}

//Function for printing spaces to the screen so the hashes will be in the right spot.
void print_spaces(int n)
{
    for (int c = 0; c < n; c++)
    {
        printf(" ");
    }
}

但得到这样的输出:

Height: 8
                 #  #
      ##  ##
     ###  ###
    ####  ####
   #####  #####
  ######  ######
 #######  #######
########  ########

我想知道我做错了什么以及如何解决它,以便顶部没有空间。记住我刚开始没有高级库或主题这是我的第一个问题集。

标签: ccs50

解决方案


如果您不希望包含 0 个哈希的行,请不要将其包含在循环中:

for (int h = 1; h <= height; h++)

从 1 开始循环会从循环中删除空行。


推荐阅读