正确对齐' #' C中的字符

时间:2016-10-10 10:27:35

标签: c cs50

所以我正在处理我的cs50问题集,并且我在输出中的字符右对齐时陷入困境。

我的程序代码(mario.c)是:

#include<stdio.h>

int main(void)
{
    int height=-1;

    while(height<0 || height>23)
    {
        scanf("%d",&height);
        printf("height: %d\n",height);
    }

    for(int i=1; i<=height; ++i)
    {
        for(int j=1;j<=i+1;++j)
        {
            printf("#");
        }
        printf("\n");
    }
}

这是我想要的输出:

Output ( that i want )

和我得到的输出:

Output ( that i am getting )

请帮帮我。提前谢谢。

3 个答案:

答案 0 :(得分:0)

首先是

printf空格。

for(int i = 1; i <= height; ++i)
{
    for (int k = 1; k <= height - i; ++k)
        printf(" ");
    for(int j = 1; j <= i + 1; ++j)
    {
        printf("#");
    }
    printf("\n");
}

答案 1 :(得分:0)

您可以使用for (int i = 0; i < popsize; i++) { individuals.add(new Individual(i+1, jobs, machines, genesPlate)); } 获取包含正确数量this.id = id; this.genesPlate = plate; this.jobs = jobs; this.machines = machines; ArrayList<Job> l1 = null; // shuffle list of jobs of each machine for (int i = 0; i < machines.length; i++) { l1 = genesPlate.get(machines[i].getId()); long seed = System.nanoTime(); Collections.shuffle(l1, new Random(seed)); genesPlate.put(machines[i].getId(), l1); } System.out.println("Reshuffled: " + genesPlate); computeFitness(); 的字符串,然后使用适当的printf format specifiers进行打印,如下所示:

sprintf

会发生什么?我们来看看#参数。

for (int i = 1; i <= height; ++i)
{
  char *buf = malloc(i + 2);
  buf[i+1] = '\0';
  for (int j = 0; j < i + 1; j++)
  {
    sprintf(buf + j, "#"); // add a new # character after the last one
  }      
  printf("%*s\n", height + 1, buf);
  free(buf);
}

答案 2 :(得分:0)

printf中添加宽度,以便打印右对齐数据。

for(int i=1;i<=height;++i)
{


    printf("%*c",(height + 1-i),'#');  //* to add width of size (height + 1-i)

    for( int j=1;j<=i;++j)
    {

        printf("#");

    }

    printf("\n");
}