用c++编写圣诞树代码
时间: 2024-06-14 13:04:34 浏览: 9
以下是一个用C++编写的圣诞树代码的例子:
```cpp
#include <iostream>
using namespace std;
int main() {
int height;
cout << "请输入圣诞树的高度:";
cin >> height;
for (int i = 0; i < height; i++) {
for (int j = 0; j < height - i - 1; j++) {
cout << " ";
}
for (int k = 0; k < 2 * i + 1; k++) {
cout << "*";
}
cout << endl;
}
for (int i = 0; i < height - 1; i++) {
cout << " ";
}
cout << "*" << endl;
return 0;
}
```
这段代码会根据用户输入的高度打印出一个圣诞树形状的图案。用户需要输入一个整数作为圣诞树的高度,然后程序会根据输入的高度打印出相应的圣诞树。
相关问题
用c++写圣诞树代码
以下是一个使用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 <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`函数来设置控制台输出的文本颜色。通过调用不同的颜色代码,我们可以实现彩色的圣诞树效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)