计算嵌套For循环的值时出现问题

时间:2013-10-16 23:57:56

标签: c++

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

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 个答案:

答案 0 :(得分: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++)
  ...

答案 1 :(得分: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;
}

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

答案 2 :(得分: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;
}

此代码的输出为

enter image description here

答案 3 :(得分: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; 

    }
相关问题