为什么我得到一条不存在的新行

Why do I get a new line which is not there

我正在学习 C,当我编写以下代码并编译它时,多打印了一行。

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

int main(void)
{
    //set the int for height
    int height;
    //using do while loop to get the numbers between 1 to 8
    do
    {
        //using get_int helps get the positive number
        height = get_int("How High should be your Pyramid (Choose Between 1 - 8): ");
    }
    //this condition helps locking the numbers entered between 1 to 8
    while (height < 1 || height > 8);
    //for loop used for drawing # on screen at required hight entered by the user
    for (int i = 0; i <= height ; i++)
    {
        //BlankSpace int is used to find the number of blank spaces to move # to the right
        int BlankSpace = height - i;
        for (int k = 0; k < BlankSpace; k++)
        {
            //prints blank space to move right
            printf(" ");
        }
        //this will print # after the blank space
        for (int j = 0; j < i; j++)
        {
            printf("#");
        }
        // move to new line
        printf("\n");
    }
}

当我编译 运行 文件时,这是它输出的内容:
$ How High should be your Pyramid (Choose Between 1 - 8):
当我们提供从 1 到 8 的任何值时,它应该看起来像这样

$ How High should be your Pyramid (Choose Between 1 - 8): 8
       #
      ##
     ###
    ####
   #####
  ######
 #######
########
$

但我得到的是以下内容:

$ How High should be your Pyramid (Choose Between 1 - 8): 8

       #
      ##
     ###
    ####
   #####
  ######
 #######
########
$

如您所见,

之间有一条线
$ How High should be your Pyramid (Chose Between 1 - 8): 8

       #

记住 $ 是 shell 提示符。

在这个循环中

for (int i = 0; i <= height ; i++)

第一次运行时,i0。因此,打印 #for (int j = 0; j < i; j++) 循环在该迭代中运行了零次。所以第一行不会打印#,但是printf("\n");还是会出现,结果就是打印了一个空行。

解决这个问题的一种方法是从 for (int i = 1; 而不是 0 开始。

get_int()的定义是什么?我认为它将 '\n' 放入标准输出缓冲区。 如果您删除 height = get_int("How High should be your Pyramid (Chose Between 1 - 8): "); 并分配 height = 8;,您的 "problem" 就会消失。