用c++写圣诞树代码
时间: 2024-03-13 10:39:28 浏览: 19
以下是一个使用C++编程语言编写的简单圣诞树代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int rows = 5; // 圣诞树的行数
for (int i = 1; i <= rows; i++) {
// 打印空格
for (int j = 1; j <= rows - i; j++) {
cout << " ";
}
// 打印星号
for (int k = 1; k <= 2 * i - 1; k++) {
cout << "*";
}
cout << endl;
}
// 打印树干
for (int i = 1; i <= rows - 1; i++) {
cout << " ";
}
cout << "*" << endl;
return 0;
}
```
这段代码使用嵌套的循环和条件语句来构建一个简单的圣诞树图案。它首先打印一定数量的空格,然后打印一定数量的星号,形成圣诞树的每一行。最后,它打印一个树干,由一个空格和一个星号组成。
相关问题
c++动态圣诞树代码
以下是一个简单的C++动态圣诞树代码示例:
```cpp
#include <iostream>
#include <string>
int main() {
int height;
std::cout << "请输入圣诞树的高度:";
std::cin >> height;
for (int i = 0; i < height; i++) {
std::string spaces(height - i - 1, ' ');
std::string stars(2 * i + 1, '*');
std::cout << spaces << stars << std::endl;
}
std::string trunkSpaces(height - 1, ' ');
std::cout << trunkSpaces << "*" << std::endl;
return 0;
}
```
这段代码会根据用户输入的高度打印出一个圣诞树形状的图案。用户需要输入一个整数作为圣诞树的高度,然后使用循环和字符串拼接来打印出相应的图案。圣诞树的每一行由空格和星号组成,最后一行只有一个星号作为树干。
C++彩色圣诞树代码
很高兴为您解答。下面是一个使用C++编写的彩色圣诞树代码示例:
```cpp
#include <iostream>
#include <windows.h>
int main() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// 设置绿色
SetConsoleTextAttribute(hConsole, 10);
std::cout << " *\n";
std::cout << " ***\n";
std::cout << " *****\n";
std::cout << " *******\n";
std::cout << " *********\n";
std::cout << "***********\n";
// 设置红色
SetConsoleTextAttribute(hConsole, 12);
std::cout << " |||\n";
std::cout << " |||\n";
// 设置黄色
SetConsoleTextAttribute(hConsole, 14);
std::cout << " |||\n";
std::cout << " |||\n";
// 设置白色
SetConsoleTextAttribute(hConsole, 15);
std::cout << " |||\n";
std::cout << " |||\n";
// 设置彩色
SetConsoleTextAttribute(hConsole, 11);
std::cout << " *****\n";
std::cout << " *******\n";
std::cout << " *********\n";
std::cout << "***********\n";
// 恢复默认颜色
SetConsoleTextAttribute(hConsole, 7);
return 0;
}
```
这段代码使用了Windows API中的`SetConsoleTextAttribute`函数来设置控制台输出的文本颜色。通过调用不同的颜色代码,我们可以实现彩色的圣诞树效果。