【问题标题】:How to build the half-left corner pyramid in c如何在c中构建左半角金字塔
【发布时间】:2016-08-31 09:45:13
【问题描述】:

我要建左半金字塔

       ##
      ###
     ####
    #####
   ######
  #######
 ########
#########

这是我的代码:

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

int main(void)
{
    printf("Enter the height of the pyramid:");
    unsigned int height = GetInt();
    int counter;

    while(height <1 || height >23){
        printf("Incorect number,try again:");
        height = GetInt();
    }

    for(counter = 2;counter <=height+1;++counter) {
        printf("%.*s\n", counter, "##############################");
    }



}

我建造了金字塔,但不是左角,而是右角金字塔。 怎样才能把它转到左边呢?

PS 我知道,在这种情况下使用 printf 并不是最好的主意,但有人告诉我用这个命令创建代码。

【问题讨论】:

  • printf("%*.*s\n", height+1, counter,...
  • @BLUEPIXY 谢谢,它有效。但是,你能解释一下这个 coude 是做什么的吗?我的意思是每个输入(尤其是第一个)。
  • printf
  • @BLUEPIXY 现在我明白了。谢谢
  • @BLUEPIXY 考虑回答让 OP 接受。

标签: c string loops cs50


【解决方案1】:

试试这个:

#include <stdio.h>

int main()
{
    int n,i,j,k;
    printf("How many lines long ?\n");
    scanf("%d",&n);

    for(i = 0; i<=n; i++)
    {
        for(j = 0; j<n-i; j++)
        {
            printf(" ");
        }
        for(k = 0; k<i; k++)
        {
            printf("#");
        }
        printf("\n");
    }
    return 0;
}

输出:

How many lines long ?
10

         #
        ##
       ###
      ####
     #####
    ######
   #######
  ########
 #########
##########


#include <stdio.h>

int main()
{
    int n,i,j,k;
    printf("How many lines long ?\n");
    scanf("%d",&n);
    n++;
    for(i = 0; i<=n; i++)
    {
        for(j = 0; j<n-i; j++)
        {
            printf(" ");
        }
        for(k = 0; k<i; k++)
        {
            if(i == 1)
            {
                continue;
            }
            printf("#");
        }
        printf("\n");
    }
    return 0;
}

Output:
How many lines long ?
10


         ##
        ###
       ####
      #####
     ######
    #######
   ########
  #########
 ##########
###########

【讨论】:

    猜你喜欢
    • 2020-02-11
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2021-12-30
    • 2021-12-15
    • 2019-05-22
    相关资源
    最近更新 更多