在C++中使用嵌套 for 循环的更复杂的形状

More complex shapes using nested for loops in C++

本文关键字:复杂 循环 for C++ 嵌套      更新时间:2023-10-16

我见过一些人做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 = 20func定义为

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艺术"。