【问题标题】:Ribbon shape using for loop in C++在 C++ 中使用 for 循环的功能区形状
【发布时间】:2018-05-18 12:23:52
【问题描述】:

我整天都在尝试在 c++ 中创建不同的 for 循环组合,但我似乎找不到正确的组合。

我希望我的输出如下所示:

Ribbon

不使用数组如何显示?

编辑:我试过这样,但我无法在另一端复制它。这是迄今为止我得到的最接近的输出。

for(int i = 0; i < 6; i++)
{
    cout<<"*";

    for(int j = 5; j > i; j--)
    {
        cout<<" ";
    }

    for(int k = 0; k <= i; k++)
    {
        cout<<"*";
    }

    cout<<endl;

}

输出:

Fail ribbon

【问题讨论】:

  • 这听起来很像一个家庭作业问题。如果它们接近工作,展示一些你尝试过的东西可能会有所帮助。

标签: c++ loops for-loop


【解决方案1】:

你有九行;让我们将它们编号为 0 到 8。行号 n 包含:

  • 1 + (4 - abs(4 - n)) 星号(1、2、3、4、5、4、3、2、1)
  • 2 * abs (4 - n) 空格(8、6、4、2、0、2、4、6、8)
  • 1 + (4 - abs(4 - n)) 星号(1、2、3、4、5、4、3、2、1)

【讨论】:

    【解决方案2】:

    一种选择是增加每行的星数,然后在到达中点后返回。

    void printChar(char c, int count)
    {
        for (int i = 0; i < count; i++)
            std::cout << c;
    }
    
    int main()
    {
        const int len = 10;
    
        int stars = 0;
    
        while (++stars <= len / 2)
        {
            int spaces = len - stars * 2;
    
            printChar('*', stars);
            printChar(' ', spaces);
            printChar('*', stars);
            std::cout << "\n";
        }
        stars--;
        while (--stars > 0)
        {
            int spaces = len - stars * 2;
    
            printChar('*', stars);
            printChar(' ', spaces);
            printChar('*', stars);
            std::cout << "\n";
        }
    
        return 0;
    }
    

    【讨论】:

    • 请不要发布一大段代码作为没有解释甚至cmets的答案。尤其是像这样的家庭作业问题。 OP 将如何从逐字复制完整的解决方案中学到任何东西?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多