21xrx.com
2025-03-30 10:31:18 Sunday
文章检索 我的文章 写文章
C++代码:如何输出圣诞树图形
2023-06-28 05:19:06 深夜i     16     0
C++ 输出 圣诞树 图形

在这个即将到来的圣诞节,你是否想用C++代码来输出一棵漂亮且充满节日气氛的圣诞树呢?那么,接下来就跟着我一起学习吧!

首先,我们需要使用C++的输出语句来描绘树干和树枝,代码如下:

cout << "      *      " << endl;
cout << "     ***     " << endl;
cout << "     *****     " << endl;
cout << "    *******    " << endl;
cout << "    *********    " << endl;
cout << "   ***********   " << endl;
cout << "   *************   " << endl;
cout << "  ***************  " << endl;
cout << "      *      " << endl;
cout << "      *      " << endl;

接下来,我们可以用循环语句来描绘树上的装饰和礼物,代码如下:

for(int i=1; i<=5; i++){ 
  for(int j=1; j<=6-i; j++)
   cout<<" "// 输出空格
 
  for(int k=1; k<=2*i-1; k++){
   cout<<"*"// 输出“*”代表树上的装饰
  }
  cout<<endl; // 输出换行符
}
for(int i=0; i<5; i++){
  for(int j=0; j<=15; j++){
   if(j==3+i || j==12-i){ // 在相应的位置输出礼物
     cout<<"$";
   }else
     cout<<" ";
   
  }
  cout<<endl;
}

最后,我们将两部分代码整合起来,就可以输出一棵漂亮的圣诞树了,完整代码如下:

#include<iostream>
using namespace std;
int main(){
  // 输出树干和树枝
  cout << "      *      " << endl;
  cout << "     ***     " << endl;
  cout << "     *****     " << endl;
  cout << "    *******    " << endl;
  cout << "    *********    " << endl;
  cout << "   ***********   " << endl;
  cout << "   *************   " << endl;
  cout << "  ***************  " << endl;
  cout << "      *      " << endl;
  cout << "      *      " << endl;
  // 输出树上的装饰和礼物
  for(int i=1; i<=5; i++){ 
   for(int j=1; j<=6-i; j++)
     cout<<" "// 输出空格
   
   for(int k=1; k<=2*i-1; k++){
     cout<<"*"// 输出“*”代表树上的装饰
   }
   cout<<endl; // 输出换行符
  }
  for(int i=0; i<5; i++){
   for(int j=0; j<=15; j++){
     if(j==3+i || j==12-i){ // 在相应的位置输出礼物
      cout<<"$";
     }else
      cout<<" ";
    
   }
   cout<<endl;
  }
  return 0;
}

当运行完整代码后,你会看到一棵充满圣诞气息的漂亮圣诞树,赶紧试一试吧!

  
  

评论区

请求出错了