21xrx.com
2024-06-03 04:47:21 Monday
登录
文章检索 我的文章 写文章
C++编写圣诞树的代码
2023-07-13 02:58:33 深夜i     --     --
C++ 编写 圣诞树 代码

在圣诞节来临之际,为了让电脑界面也能洋溢着节日的气氛,我们可以使用C++编写一个圣诞树的代码。

首先,我们需要在控制台中输出圣诞树的形状。这可以通过使用循环嵌套来实现。在循环中,我们需要输出由空格和星号组成的字符串。空格可以用来控制星号的位置,从而使得输出的字符串呈现出树形状。

接下来,我们需要添加圣诞树的装饰物,例如彩灯和星星。这些元素可以通过在输出的字符串中添加字符来实现。例如,星星可以用五角星或者点来表示,而彩灯可以用井号或者小圆点来表示。

最后,我们需要让圣诞树在控制台中动起来。这可以通过循环输出不同的树形字符串来实现。每次输出字符串后,我们可以通过清空控制台的命令来清空之前的输出,从而达到动画效果。

以下是一份简单的代码示例:


#include <iostream>

#include <windows.h>

using namespace std;

int main () {

  int height = 10;

  for (int i = 0; i < height; ++i) {

    for (int j = 0; j < height-i-1; ++j)

      cout << " ";

    

    for (int k = 0; k < i * 2 + 1; ++k) {

      cout << "*";

    }

    cout << endl;

  }

  

  for (int i = 0; i < 5; ++i) {

    for (int j = 0; j < height-2; ++j)

      cout << " ";

    

    cout << "*";

    cout << endl;

  }

  

  for (int i = 0; i < 4; ++i) {

    for (int j = 0; j < height-3; ++j)

      cout << " ";

    

    cout << "***";

    cout << endl;

  }

  

  for (int i = 0; i < 5; ++i) {

    for (int j = 0; j < height-2; ++j)

      cout << " ";

    

    cout << "*";

    cout << endl;

  }

  

  int time = 0;

  while (time < 20) {

    Sleep(250);

    system("cls");

    for (int i = 0; i < height; ++i) {

      for (int j = 0; j < height-i-1; ++j)

        cout << " ";

      

      for (int k = 0; k < i * 2 + 1; ++k) {

        if (k % 2 == 0)

          cout << ".";

         else {

          cout << ".";

        }

      }

      cout << endl;

    }

    

    for (int i = 0; i < 5; ++i) {

      for (int j = 0; j < height-2; ++j)

        cout << " ";

      

      cout << "*";

      cout << endl;

    }

    

    for (int i = 0; i < 4; ++i) {

      for (int j = 0; j < height-3; ++j)

        cout << " ";

      

      cout << "***";

      cout << endl;

    }

    

    for (int i = 0; i < 5; ++i) {

      for (int j = 0; j < height-2; ++j)

        cout << " ";

      

      cout << "*";

      cout << endl;

    }

    time += 1;

  }

  

  return 0;

}

上述代码输出的圣诞树形状及动画如下图所示。通过不断调整代码及控制台输出的样式,我们可以编写出更加精美、生动的圣诞树代码。

![圣诞树动画效果](https://pic.imgdb.cn/item/61e97ee8744acf3b84396007.gif)

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复