如何在c++中获得沙漏模式

How to get an Hourglass pattern in c++

本文关键字:沙漏 模式 c++      更新时间:2023-10-16

我一直在试图得到这个沙漏模式,一段时间以来,我一直被困在如何进行,它要求用户输入#'s的数量在顶行,并指出行数。如果#的个数小于3,则打印一条错误消息。如果行数少于1,或者少于2个"#",则无效。

无论如何,如果我输入7作为第一行,3作为行数,我一直得到这个模式。

7 # s在顶部

5 #'s

3 #'s

3 #'s

5 #'s

我不需要有3 #的行但我似乎无法摆脱它

下面是我的代码:
   // Declare and initialize variables
    int topRow(0);
    int row(0);
    int i(0);
    int k(0);
    int j(0);

  // Repeatedly prompt for top row size until valid value is entered
cout << "Enter size of the top row: " ;
cin >> topRow;
    while(topRow < 3)
    {
    cout << "Size of the top tow must be at least three." << endl;
    cout << "Enter size of the top row again: "; 
    cin >> topRow;
    }

  // Repeatedly prompt for the number of rows until valid value is entered
cout << "Enter number of rows: ";
cin >> row;
    while(row == 0 || topRow/row < 2.0  || row < 1.0 )
    {
    cout << "Invalid number of rows." << endl;
    cout << "Enter number of top row again: "; 
    cin >> row;
    }

  // Print the hour glass
cout << endl;
    for (i=1; i < topRow ; i++)
    {
        if (i <= row )
        {   for (j=1; j <= i-1; j++)
            { 
            cout << " ";
            }
            for (k=1; k <= topRow - (i*2 - 2) ; k++)
            {
            cout << "#";
            }
            cout << endl;
        }
        else 
        {   
            for (j = row ; j >= i - (row - 1); j--)
            {
                cout << " ";
            }
            for (k = row ; k >= topRow - (i*2 - 2); k--)
            {
               cout <<"#";
            }
            cout << endl;
        }
}
  // end program
  return 0;

您可以在沙漏的后半部分的第一次迭代中添加检查。如果

虽然很乱,那就像这样:

static bool first = true;
if (first) {
  first = false;
} else {
  // ... second print code
}

7和3的输入现在是:

#######
 #####
  ###
 #####
#######

如果你期望其他输入被正确格式化,你有一个更大的问题。
我建议你修改一下你的算法。