2

中空の長方形を作成する必要がありますが、使用できるループは 1 つだけです。プログラムはそのまま動作しますが、コードで 2 つのループを使用しており、最後のループを減らす方法がわかりません。(printf、scanf、if/else、ループのみを学習したため、配列などはありません。) プログラムは、フレームの高さ、幅、および厚さをスキャンします。

誰かが私を正しい方向に向けることができますか?

コードは次のようになります。

row = 0;
while(row < height)
{
    column = 0;
    while(column < width)
    {
        if(thickness > row)    // upper border
            { printf("*");};
        if( some conditions )  // left border
            { printf("*");};
        if( conditions )    // hollow
            { printf(" ");};
        if( conditions )   // right border
            { printf("*");};
        if( conditions )     // bottom border
            { printf("*");};

        column++;
    };

puts("");
row++;
};
4

3 に答える 3

1

完全に立ち往生している場合、または別の解決策を見たい場合にのみ読んでください。
ご覧のとおり、入力のスキャンはありません。

#include <stdio.h>

int main(void)
{
  int width=5;
  int height=6;
  int thick=1;
  int x=1;
  int y=height;

  while(y>0)
  {
    if(y>(height-thick) || y<=thick || x<=(thick) || x>(width-thick))
      printf("*");
    else
      printf(" ");
    if(x==width)
    {
      x=1;
      printf("\n");
      y--;
    }
    else
    {
      x++;
    }
  }
  return 0;
}
于 2013-10-07T20:51:11.800 に答える
0

以下のコードを使用すると、フレームを印刷できます1loop+ if-else2*column+width-2

    int i, column = 6,width=5;

        for(i=1;i<=2*column+(width-2);i++) 
        {
               if( i <= column || i-column>=width-1) 
               printf("* ");
               else    
               printf("\n*%*s\n",2*(column-1),"*");  // prints newline and `*` then Width of 2*(colomn-1) times space and  again * and newline.  
               //if you don't want newline two times, remove trailing one add if statement inside else check i==column+width-2 print newline. 
        };  

一般化。

#include <stdio.h>

int main(void) {
int i, column ,width;
printf("Enter two");
scanf("%d%d",&column,&width);
    for(i=1;i<=2*column+(width-2);i++)
    {
           if(i <= column || i-column>=width-1)
           printf("*");
           else
            {
            printf("\n*%*s",(column-1),"*");
            if (i-column==width-2)
            printf("\n");
            }
    };

    printf("\n");
        return 0;
}
于 2013-10-07T21:08:46.743 に答える