你怎么做沙漏模式?

时间:2016-03-12 04:20:40

标签: c++

我试图制作一个沙漏,但我无法获得沙漏的代码。我究竟做错了什么?这是原始代码的较短版本。

#include <iostream>

using std::cin; using std::cout; using std::endl;

int main()
{
    int number;
    cin >> number;

//Hourglass

   for (i = number; i > 0; i--)
   {
       cout << endl;
       for (int j = number; i < j; j--)
       {
           cout << " ";
       }
       for (int j = 0; i > j; j++)
       {
           cout << "*";
       }
       for (int j = 0; i > j; j++)
       {
           cout << "*";
       }
   }
   for (int i = 0; i < number; i++)
   {
       for (int j = 0; j < (number - (i + 1)); j++)
       {
           cout << " ";
       }
       for (int j = 0; j < (2 * i + 1); j++)
       {
           cout << "*";
       }
       for (int j = 0; j < (number - (i + 1)); j++)
       {
           cout << " ";
       }
       cout << endl;
   }
}

2 个答案:

答案 0 :(得分:0)

问题出在你的第一个for循环中。您需要做的是移动

cout << endl; 

到循环的底部,以便在进入第二个循环之前创建一个新行。

    for (int i = number; i > 0; i--){
        for (int j = number; i < j; j--)
        {
            cout << " ";
        }
        for (int j = 0; i > j; j++)
        {
            cout << "*";
        }
        for (int j = 0; i > j; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    for (int i = 0; i < number; i++)
    {
        for (int j = 0; j < (number - (i+1)); j++)
        {
            cout << " ";
        }
        for (int j = 0; j <= (2 * i) + 1; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

这会给你一个像这样的沙漏

**********
 ********
  ******
   ****
    **
    **    
   ****   
  ******  
 ******** 
**********

答案 1 :(得分:0)

以下代码将在屏幕上打印沙漏(*)图案。变量 size 是要打印的沙漏的高度。使用g ++编译器编译代码。

#include <iostream>

int main() {

  int row, col;
  int size;
  int diagA, diagB;

  std::cout << "Enter height of the hourglass ";
  std::cin >> size;

  for ( row=0; row<size; row++ ) {
    for ( col=0; col<size; col++ ) {

      diagA = row;
      diagB = size-row-1;

      if ( diagA <= diagB ){
        if ( col >= diagA && col <= diagB )
          std::cout << "*";
        else
          std::cout << " "; 
      }
      else {
        if (  col >= diagB && col <= diagA  )
          std::cout << "*";
        else
          std::cout << " ";
      }
    }
    std::cout << std::endl;
  }

  std::cout << std::endl;

  return 0;
}