c++空心正方形星号列阵
时间: 2024-01-31 10:10:16 浏览: 24
以下是C++中打印空心正方形的代码示例:
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
if (n == 1) {
cout << "*";
} else {
for (int i = 0; i < n; i++) {
cout << "*";
}
cout << endl;
for (int i = 0; i < n - 2; i++) {
cout << "*";
for (int j = 0; j < n - 2; j++) {
cout << " ";
}
cout << "*" << endl;
}
for (int i = 0; i < n; i++) {
cout << "*";
}
}
return 0;
}
```
相关问题
c++倒三角星号列阵
以下是两种C++倒三角星号列阵的例子:
1. 使用三个for循环语句输出倒三角星号列阵:
```cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 9; i >= 1; i--) {
for (int j = 1; j <= 9 - i + 1; j++) {
cout << " ";
}
for (int k = 1; k <= 2 * i - 1; k++) {
cout << "*";
}
cout << endl;
}
system("pause");
return 0;
}
```
2. 使用四个for循环语句输出倒三角星号列阵:
```cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 10; i <= 19; i++) {
for (int j = 0; j <= i - 10; j++) {
cout << " ";
}
for (int k = 1; k <= 2 * (19 - i) - 1; k++) {
cout << "*";
}
cout << endl;
}
system("pause");
return 0;
}
```
c++输出星号金字塔
以下是C++输出星号金字塔的代码,其中使用了双重for循环来实现:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
cout << " ";
}
for (int j = 1; j <= i * 2 - 1; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}
```
这段代码可以输出一个高度为n的星号金字塔,其中第i行有i*2-1个星号,每行星号前面有n-i个空格。