如何在C ++中获得沙漏图案 [英] How to get an Hourglass pattern in c++

查看:77
本文介绍了如何在C ++中获得沙漏图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试获得这种沙漏模式,有一段时间了,我一直坚持如何进行操作,它要求用户在第一行中输入#的数目并指出行数.如果#的数量少于3,则会显示一条错误消息.如果行数少于1,则无效,或者行数少于2'#'.

I have been trying to get this hourglass pattern, for a while now and I have been stuck on how to proceed, it require the user to input the number of #'s in the top row and to indicate the number of rows. If the number of #'s is less than 3 it prints an error message. If the number of rows is less than 1 it is invalid or if it has less than 2 '#' 's .

无论如何,如果我在第一行输入7,在行数输入3,我仍然会得到这种模式.

顶部7个

5#位于下一行

3#位于下一行

3#位于下一行

5#位于下一行

7#位于下一行

我不需要带有3号的行之一,但是我似乎无法摆脱它.

And I don't need one of the rows with 3 #'s but I can't seem to get rid of it.

无论如何,这是我的代码:

Anyway here is my code :

   // 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;

推荐答案

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

You could add a check to the first iteration of the second half of the hourglass. If

尽管很杂乱,但这样:

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

现在输入7和3将是:

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


如果您期望其他输入格式正确,那么您会遇到更大的问题.
我建议您重做算法.


If you are expecting other inputs to be correctly formatted, you have a much larger problem.
I suggest you rework your algorithm.

这篇关于如何在C ++中获得沙漏图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆