0

我需要通过以下方式打印星号:

xxxxxxx
_xxxxx
__xxx

(7, 5, 3)

或者

xxxxxx
_xxxx
__xx

(6, 4, 2)

有一个用于最高星号数的输入和一个用于行数的输入。底行的星号不得少于两个。

我意识到这需要一个嵌套for循环。

我有以下代码:

  for (rows = 1; rows < ((toprow / 2) + (toprow % 2)); rows++)
    {
      for ()
      cout << endl;                                    
    }

我很难弄清楚内部for循环。

4

4 回答 4

3
for (rows = 1; rows < ((toprow / 2) + (toprow % 2)); rows++)
  {
    if(rows <= maxrows)
      {
        // first the leading underscores
        for (int k=1; k<rows; ++k)
          cout << "_";

        // then the asterisks
        for (int k=1; k <= toprow - 2*rows + 2; ++k)
          cout << "*";
        cout << endl;                                    
      }
  }

编辑:您的外部循环不会迭代正确的行数。应该是这样的:

for (int rows = 1; rows <= (toprow / 2); rows++)
  ...
于 2013-10-17T00:10:33.400 回答
0

你可能想要这样的东西:

int initial = 7;
int copy = initial;
int rows = 3;
for (int i = 0; i < rows; i++)
{
    std::cout << std::string(initial - copy, ' ')
              << std::string(copy, '*') << std::endl;
    copy -= 2;
}

这是假设提供的行作为有效输入。

于 2013-10-17T00:10:44.580 回答
0

将此 C 代码用作参考。它将打印最多行数或当最后一行开始小于 2 时,以较早者为准。

    #include<stdio.h>
    int main()
    {
    //topstar have the number of stars in top row
    int row=7;
    int topstar=7;
    int i,j,k,l,last;

    for(i=0;i<row;i++)
    {
    //last contain the number of stars in last row
    last=topstar - 2*i;

    if(last<2)
     break;

     for(k=0;k<i;k++)
       printf("_");
    for(j=0;j<last;j++)
       printf("*");
    for(l=0;l<i;l++)
       printf(" ");
       printf("\n");
   }
  return 0;
}

此代码的输出是

在此处输入图像描述

于 2013-10-17T00:13:27.973 回答
0
spaces = 0;
asterix = toprow;
for (rows = 1; rows < ((toprow / 2)  + (toprow % 2)) && asterix > 1; rows++)
    {
      for (i = 0; i < spaces; i++)
        print -; 

      for (i = 0; i < toprow; i++)
        print *;

      println  

      spaces+=2;
      asterix -=2; 

    }
于 2013-10-17T00:34:51.517 回答