如何使用 for 环制作螺旋桨形状

How to make a Propeller shape Using For-Loops?

本文关键字:螺旋桨 何使用 for      更新时间:2023-10-16

我们被要求创建一个程序,该程序将生成由四个直角三角形组成的螺旋桨形状。大小取决于输入。

示例输出如下所示:

Enter a number for the size: 5
         *****
    *    ****
    **   ***
    ***  **
    **** *
    ***** *****
         * ****
        **  ***
       ***   **
      ****    *
     *****

这是我到目前为止的代码:但我的错误是我的输出不完全是它应该的样子......一个三角形没有对齐。可能是什么原因?

                this is my output :
                   *****
              *    ****
              **   ***
              ***  **
              **** *
              ***** 
                   * *****
                  **  ****
                 ***   ***
                ****    **
               *****     *

法典:

#include <iostream>
using namespace std;
int main ()
{
    int size;
    cout << "Enter a number for the size : " ;
    cin >> size;
    cout <<endl;
    for (int ctr = 0; ctr <= size; ctr++)
    {
        for(int x = 0; x < ctr; x++)
        {
            cout << "*";
        }
        for (int space=size; space >ctr;space--)
        {
            cout <<" ";
        } 
        for (int x2=size; x2 >ctr; x2--)
        {
            cout<<"*";
        };
        cout<<endl;
    }
    for (int ctr2 = 0; ctr2 <=size; ctr2++)
    {
        for (int space2=size; space2 >ctr2; space2--)
        {
            cout<<" ";
        } 
        for (int x3=0; x3 <=ctr2; x3++)
        {
            cout<<"*";
        };
        for (int space3=0; space3<=ctr2;space3++)
        {
            cout<<" ";
        }
        for (int x4=size; x4>=ctr2;x4--)
        {
            cout<<"*";
        }
        cout <<endl;
    }
    return 0;
}

由于这是家庭作业,我不想完全解决此任务,但是在第一个 for 循环结束时,您创建了一个新行 ( cout<<endl )。但是,右上角三角形的第一行从第一个三角形的最后一行开始。最简单的方法是在单独的情况下处理中间线,当然可以调整其他循环。

尝试比较您的实际输出和预期输出,并查看第一个不同的字符(我为您做了;下面以粗体标记):

    ******    ******   ******  ****** *******     * ****    **  ***   ***   **  ****    * *****

然后确定代码中打印另一个字符的位置(为此使用调试器)。