首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环中的空间计算量

循环中的空间计算量
EN

Stack Overflow用户
提问于 2014-12-10 13:42:54
回答 1查看 553关注 0票数 0

我用C++制作了一个程序,画出一棵圣诞树,但是我对树桩有一些问题。我真的不明白为什么它不想出现在中间(与树的顶端一致,使整个树对称)。

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

以下是我到目前为止在代码方面所做的工作:

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-10 13:53:07

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

代码语言:javascript
复制
int treeWidth = treeHeight*2;

然后在后备箱前面写空格如下:

代码语言:javascript
复制
// Spaces to the center of the tree so that the stump is centered
for (int j = 0; j < treeWidth/2-1; ++j)
    cout << " ";

我还在树的最上面加了一条新的线。圣诞快乐!

代码语言:javascript
复制
                 #
                ###
               #####
              #######
             #########
            ###########
           #############
          ###############
         #################
        ###################
       #####################
      #######################
     #########################
    ###########################
   #############################
  ###############################
 #################################
###################################
                 |
                 |
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27402526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档