gpt4 book ai didi

c++ - 用 while 循环绘制一个简单的三角形

转载 作者:行者123 更新时间:2023-11-30 02:11:13 24 4
gpt4 key购买 nike

在愚蠢的生活问题使我出轨后重新学习!我决定更换我的学习 Material ,我现在正在学习 Accelerated C++。

第 2 章,练习 5:
写一组“*”字符,使它们形成一个正方形、一个长方形和一个三角形。

我试过了,但就是无法准确地放下三角形。快速谷歌找到以下答案:

// draw triangle
int row = 0;
int col = 0;
int height = 5;

// draw rows above base
while (row < height - 1)
{
col = 0;
while (col < height + row)
{
++col;
if (col == height - row)
cout << '*';
else
{
if (col == height + row)
cout << '*';
else
cout << ' ';
}
}
cout << endl;
++row;
}

// draw the base
col = 0;

while (col < height * 2 - 1)
{
cout << '*';
++col;
}

我想剖析它并完全理解它,因为我很难得出自己的答案。不管我遍历多少次,我都看不到它是如何绘制三角形的右侧的:

- - - - *
- - - *
- - *
- *
*
* * * * * * * * * *

这就是我在纸上经历的这个循环。右边到底是从哪里来的?我有一种直觉,这些表情正在做我没有看到的事情。代码有效。

最佳答案

在嵌套的 while 循环中,在 else 子句内:

else
{
if (col == height + row)
cout << '*'; // This draws the right side
else
cout << ' ';
}

诀窍是 while 循环不会退出,直到列到达 height + row,即右侧的位置。它在前面的 if 子句中更早地打印左侧(在 height - row)。

关于c++ - 用 while 循环绘制一个简单的三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3747308/

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