# c++中用for迴圈倒空心三角問題送分20點

#include &lt;stdio.h&gt;

#include &lt;stdlib.h&gt;

int main(void)

{

int a,b,i,k,p,l,c,m;

char w;

printf(&quot;輸入指定的字元&quot;);

scanf(&quot;%s&quot;,&amp;w);

printf(&quot;請輸入你要的高度&quot;);

scanf(&quot;%d&quot;,&amp;l);

c=l-3;

m=(c*2)+5;

p=l;

for(i=1;i&lt;=m;i++)

printf(&quot;%c&quot;,w);

printf(&quot;&#92;n&quot;);

for(i=2;i&lt;=l;i++)

{

for(a=2;a&lt;=i;a++)

printf(&quot; &quot;);

if(i&lt;l)

printf(&quot;%c&quot;,w);

for(k=3;k&lt;=p;k++)

printf(&quot; &quot;);

for(k=4;k&lt;=p;k++)

printf(&quot; &quot;);

printf(&quot;%c&#92;n&quot;,w);

p--;

}

system(&quot;pause&quot;);

return 0;

}

### 1 個解答

• 1 0 年前
最佳解答

#include <stdio.h&>

#include <stdlib.h&>

int main(void) {

int a,b,i,k,p,l,c,m;

// a, i, k = loop index

// b = not used

// p = rows to be drawn

// l = height of the triangle

// c = temp variable for width calculation

// m = width of the triangle

char w; // the star symbol

printf(“輸入指定的字元”); scanf(“%s”,&w); // read symbol

printf(“請輸入你要的高度”); scanf(“%d”,&l); // read height

c=l-3;

m=(c*2)+5; // calculate the width of the triangle

p=l; // rows to draw – I would move this to the second for loop below

for(i=1;i<=m;i++) printf(“%c”,w); // draw the bottom of triangle

printf(“\n”); // finish the bottom

for(i=2;i<=l;i++) { // draw one line at a time

for(a=2;a<=i;a++) printf(“ “); // draw the leading blanks

if(i<l) printf(“%c”,w); // draw the star, except for the last line

for(k=3;k<=p;k++)printf(“ “); // draw the inside of triangle, left half

for(k=4;k<=p;k++)printf(“ “); // draw the inside of triangle, right half

printf(“%c\n”,w); // draw the star at the right side

p--; // one more line has been drawn

}

system(“pause”); // keep the window open

return 0;

}