在C++中使用嵌套 for 循环的更复杂的形状
More complex shapes using nested for loops in C++
我见过一些人做X或三角形或菱形等简单的例子。我想知道如何制作这样的复杂形状:
# #
## ##
### ###
#### ####
###########
###########
#### ####
### ###
## ##
# #
我对编程非常陌生,不知道代码本身的基本功能。
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
int spaces = 4;
int hashes = 1;
for(int row=0;row<10;row++)
{
for(int spaces=0;spaces<4;spaces++)
{
cout<<" ";
}
for(int hashes=0;hashes<1;hashes++)
{
cout<<"#";
}
cout<<endl;
if(row<5&&row>6)
{
spaces--;
hashes+=2;
}
else
{
spaces++;
hashes-=2;
}
}
return 0;
}
一个简单的方法是使用"光线跟踪"方法;即
for (int y=0; y<rows; y++) {
for (int x=0; x<cols; x++) {
if (func(x, y)) {
std::cout << "#";
} else {
std::cout << " ";
}
}
std::cout << "n";
}
例如,将rows = cols = 20
和func
定义为
bool func(int x, int y) {
return (x-10)*(x-10) + (y-10)*(y-10) < 8*8;
}
你会得到一个圆圈
绘制像您这样的形状的许多任务都是基于水平和垂直方向的对称性。 例如,在水平方向上,从左到中间的字符将镜像到中心点之后。
绘制形状的老式方法是将它们存储在二维数组中,然后打印出数组:
unsigned char letter_E[7][5] =
{
{'*', '*', '*', '*', '*'},
{'*', ' ', ' ', ' ', ' '},
{'*', ' ', ' ', ' ', ' '},
{'*', '*', '*', '*', '*'},
{'*', ' ', ' ', ' ', ' '},
{'*', ' ', ' ', ' ', ' '},
{'*', '*', '*', '*', '*'},
};
for (unsigned int row = 0; row < 7; ++row)
{
for (unsigned int column = 0; column < 5; ++column)
{
std::cout << letter_E[row][column];
}
std::cout << 'n';
}
另外,在互联网上搜索"ASCII艺术"。
相关文章:
- while循环中while循环的时间复杂度是多少
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 具有嵌套 if-else 的循环的时间复杂度
- 在 for 循环中处理复杂的发送 recv 消息
- 确定 for 循环的不同大 O 复杂度
- 如果代码包含多个复杂度循环,如何计算复杂度
- 2 个嵌套循环的时间复杂度
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 带有 if 语句的嵌套循环的时间复杂度
- 双倍简单的循环与一个复杂的循环
- C++ 数组循环的时间复杂度
- 创建复杂的嵌套循环
- 基本类型和复杂类型的循环的泛型
- 在C++中使用嵌套 for 循环的更复杂的形状
- 以下循环的时间复杂度是多少
- 避免在C++循环中循环中复杂对象时最小化范围效率低下的技术
- 内部 for 循环的时间复杂度
- 嵌套循环的时间复杂度:cn(n+1)/2从何而来