c++输出星号正方形
时间: 2024-06-04 21:02:47 浏览: 17
要在C++中输出星号正方形,可以使用嵌套循环来控制行和列的数量,并使用if语句来判断是否需要输出星号或空格。以下是一个示例代码:
```
#include <iostream>
using namespace std;
int main() {
int sideLen;
cout << "请输入要打印的边长:\n";
cin >> sideLen;
for(int i = 0; i < sideLen; i++) {
for(int j = 0; j < sideLen; j++) {
if(i == 0 || i == sideLen - 1 || j == 0 || j == sideLen - 1) {
cout << "* ";
} else {
cout << " ";
}
}
cout << endl;
}
return 0;
}
```
该代码使用了两个嵌套循环来控制行和列的数量,使用if语句来判断是否需要输出星号或空格。在每一行的末尾,使用cout << endl;来换行。如果输入的边长为1,则只需要输出一个星号。
相关问题
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个空格。
c++空心正方形星号列阵
以下是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;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)