2016-10-10 5 views
-2

그래서 나는 cs50 문제 세트를 수행 중이었고 출력 결과에서 문자를 올바르게 정렬하는 데 막혔습니다.C에서 '#'문자의 오른쪽 정렬

내 프로그램 (mario.c)에 대한 코드는 다음과 같습니다

Output (that i want)

그리고 난 점점 오전 출력 :

여기
#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 am getting)

쾌락 나 좀 도와 줘. 미리 감사드립니다.

+7

올바른 갯수의 공백을 먼저 인쇄하십시오. –

+0

정확한 공백과 해시를 반복하는 대신 별표로 표시된 필드 너비와 정밀도 지정자를 사용하여 실험 할 수 있습니다. 그것은 귀하의 임무에 대한 범위를 벗어날 수 있습니다. –

답변

0

첫 번째 공백을 인쇄하십시오.

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"); 
} 
0

당신은 #의 적당한 양을 포함하는 문자열을 얻을 다음 사용하므로 같은 apropriate 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); 
} 

를? printf 매개 변수를 살펴 보겠습니다.

"%*s"  // % means to start a placeholder 
      // * tells this placeholder to reserve at least as many 
      // characters as we tell it to via an variable 
      // s tells printf that this is a placeholder for a string 

height + 1 // reserver height + 1 character 

buf  // stores the correct ammount of # 
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"); 
}