在C++中,如何编写代码来打印一个正六边形图案?
时间: 2024-10-27 20:03:41 浏览: 46
在C++中,可以使用嵌套循环以及一些简单的算术运算来打印出一个正六边形图案。这里是一个基本的例子,用于打印6行的正六边形:
```cpp
#include <iostream>
using namespace std;
// 定义六边形函数
void printHexagon(int n) {
int i, j, space;
for (i = 0; i < n; i++) {
// 打印空格
space = n - i - 1;
cout << " ";
for (j = 0; j < 2 * i + 1; j++) {
// 打印星号(*)
if (j == 0 || j == 2 * i)
cout << "*";
else
cout << " ";
}
cout << endl; // 每行结束后换行
}
}
int main() {
int rows;
cout << "Enter the number of rows for the hexagon: ";
cin >> rows;
printHexagon(rows);
return 0;
}
```
在这个程序中,用户会被提示输入想要的六边形行数,然后`printHexagon`函数会打印相应的图案。每一行的开始和结束都有一定的空格,而在正六边形的顶点处则是星号(*)。
阅读全文
相关推荐














