gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:23:54 25 4
gpt4 key购买 nike

我想像这样在屏幕上打印一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com