for循环中的空间量计算

时间:2014-12-10 13:42:54

标签: c++ for-loop

我用C ++编写了一个程序来绘制一棵圣诞树,但是我遇到了一些问题。我真的不明白为什么它不想出现在中间(与树的顶部对齐,使整个树对称)。

我已经嵌套for循环但是,我计算正确的空格吗?

以下是我目前在代码方面的内容:

int treeHeight;

int main()
{
    cout << "Enter the size of the tree (4-20): ";
    cin >> treeHeight;

    void getValidHeight();
    getValidHeight();

    // Set tree height to 2 lower than it is (part of spec I'm following)
    treeHeight = treeHeight - 2;

    // Set tree character 
    char leaf = '#';

    // Set tree stump character 
    char treeStump = '|';

    // First leaf (top of tree)
    int leaves = 1;

    int treeWidth = treeHeight / 2;

    int stumpHeight = 2;

    for (int total = treeHeight; total > 0; --total)
    {
        //control the amount of spaces
        for (int i = (total - 1); i > 0; --i)
            cout << " ";

        //control the amount of leaves
        for (int j = 0; j < leaves; ++j)
        {
                cout << leaf;
        }

        // Next row needs 2 extra leaves
        leaves += 2;

        cout << '\n';
    }

    // Create the stump
    for (int i = 0; i < stumpHeight; ++i)
    {
        // Spaces to the center of the tree so that the stump is centered
        for (int j = 0; j < treeWidth; ++j)
            cout << " ";

        for (int k = 0; k < 1; ++k)
            cout << treeStump;

        cout << '\n';
    }

    system("pause");
    return 0;
}

void getValidHeight()
{
    while (treeHeight > 20 || treeHeight < 4)
    {
        cout << "\nEROOR: Invalid height! Enter the size of the tree (4-20): ";
        cin >> treeHeight;
    }
}

1 个答案:

答案 0 :(得分:1)

因为树的宽度不是树高的一半!例如,尝试将宽度更改为

int treeWidth = treeHeight*2;

然后在行李箱之前写下空格,如下所示:

// Spaces to the center of the tree so that the stump is centered
for (int j = 0; j < treeWidth/2-1; ++j)
    cout << " ";

我还在树前面的最顶部添加了一个新行。圣诞快乐!

                 #
                ###
               #####
              #######
             #########
            ###########
           #############
          ###############
         #################
        ###################
       #####################
      #######################
     #########################
    ###########################
   #############################
  ###############################
 #################################
###################################
                 |
                 |