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

希望有人能將以下的程式後加讓註解 及 為什麼要這麼做

研究半天弄不出個所以然~"~

#include <stdio.h>

#include <stdlib.h>

int main(void)

{

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

char w;

printf("輸入指定的字元");

scanf("%s",&w);

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

scanf("%d",&l);

c=l-3;

m=(c*2)+5;

p=l;

for(i=1;i<=m;i++)

printf("%c",w);

printf("\n");

for(i=2;i<=l;i++)

{

for(a=2;a<=i;a++)

printf(" ");

if(i<l)

printf("%c",w);

for(k=3;k<=p;k++)

printf(" ");

for(k=4;k<=p;k++)

printf(" ");

printf("%c\n",w);

p--;

}

system("pause");

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;

    }

還有問題?馬上發問,尋求解答。