c++ - 在屏幕上打印 X 的形状

标签 c++

我想像这样在屏幕上打印一个 X:

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

我试过这段代码:

int main(){
    bool back = false;
    for (int i = 0; i < 7; ++i) {
        if (i == 4)
            back = true;   

        if (!back){
            for (int j = 0; j < i; ++j) {
                cout << " ";
            }
        } else{
            for (int j = 7-i-1; j > 0; --j) {
                cout << " ";
            }
        }
        cout << "*" << endl;
    }
}

结果缺少右半边:

*
 *
  *
   *
  *
 *
* 

问题是我不知道如何打印星星和跟随它们的星星之间的空间。

最佳答案

解决此问题的更具教育意义的方法需要 2 个循环。

第一个 for 循环控制输出的高度,即打印的行数。每次迭代打印一行并以 std::endl 结束。

第二个 是一个嵌套的for 循环,它控制宽度 并水平打印字符,即打印星号和空格对于那条线。每次迭代打印一个空格或一个星号。

此图可能有助于理解 x_size = 5 时变量的值:

                 (width)     
             0   1   2   3   4
(height)   ---------------------
   0       | * |   |   |   | * |      asterisk_pos = 0, end_pos = 4, inc =  1
           ---------------------
   1       |   | * |   | * |   |      asterisk_pos = 1, end_pos = 3, inc =  1
           ---------------------
   2       |   |   | * |   |   |      asterisk_pos = 2, end_pos = 2, inc =  1
           ---------------------
   3       |   | * |   | * |   |      asterisk_pos = 1, end_pos = 3, inc = -1
           ---------------------
   4       | * |   |   |   | * |      asterisk_pos = 0, end_pos = 4, inc = -1
           ---------------------

源代码:

int main()
{
    int x_size = 7;        // size of the drawing
    int asterisk_pos = 0;  // initial position of the asterisk
    int inc = 1;           // amount of increment added to asterisk_pos after an entire line has been printed

    // height is the line number
    for (int height = 0; height < x_size; height++)
    {
        // width is the column position of the character that needs to be printed for a given line
        for (int width = 0; width < x_size; width++)
        {
            int end_pos = (x_size - width) - 1; // the position of the 2nd asterisk on the line

            if (asterisk_pos == width || asterisk_pos == end_pos)
                cout << "*";
            else
                cout << " ";
        }

        // print a new line character
        cout << std::endl;

        /* when the middle of x_size is reached, 
         * it's time to decrease the position of the asterisk!
         */
        asterisk_pos += inc;    
        if (asterisk_pos > (x_size/2)-1)
            inc *= -1;
    }    

    return 0;
}

x_size = 7 的输出:

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

x_size = 3 的输出:

* *
 * 
* *

关于c++ - 在屏幕上打印 X 的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48465089/

相关文章:

c++ - 参数化查询中的参数计数不匹配

c++ - 对模板类成员的 undefined reference

java - 我应该使用哪种键值数据结构?按值快速检索,按键快速检索

c++ - 如何在基类中获取派生类的子类型

c++ - 为什么包含 windows.h 时 std::min 失败?

c++ - 如何配置 CMake 以使用 -fPIC 构建库?

c++ - 为什么我在 DLL 中收到 "Unable to find an entry point named ' SquareRoot' 消息?

c++ - 隐式构造函数与 "empty"构造函数

c++ - 在函数中分配但不在外部分配的私有(private)变量

c++ - vector 的核心段错误