问题 D: 【入门】空心正方形
题目描述
打印n行的空心正方形。
输入
一个整数n(n<10)
输出
n行的空心正方形
样例输入 复制
4
样例输出 复制
****
* *
* *
****
想必大家这种题目看得多了吧
很多人还是这样做的:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n = 0;
while (cin >> n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (1 == i || i == n )
{
cout << "* "; //*号后有一个空格
}
else if (1 == j || j == n)
{
cout << "* ";
}
else
{
cout << " "; //注意为两个空格
}
}
cout << endl;
}
cout << endl;
}
}
这里,我不得不说一下
while(cin>>n)是只要你有n就输入,还要按Ctrl+R才结束,当然,测试器是不会ctrl+R的
况且思路太难理解
下面我给大家看一种用暴力解决问题:
#include<bits/stdc++.h>
using namespace std;
int n;
int main() {
cin>>n;
for(int i=1; i<=n; i++) {
cout<<"*";
}
cout<<endl;
for(int i=2; i<=n-1; i++) {
for(int j=1; j<=n; j++) {
if(j==1||j==n) {
cout<<"*";
} else {
cout<<" ";
}
}
cout<<endl;
}
for(int i=1; i<=n; i++) {
cout<<"*";
}
return 0;
}
没登录的看这里:
#include<bits/stdc++.h>
using namespace std;
int n;
int main() {
cin>>n;
for(int i=1; i<=n; i++) {
cout<<"*";
}
cout<<endl;
for(int i=2; i<=n-1; i++) {
for(int j=1; j<=n; j++) {
if(j==1||j==n) {
cout<<"*";
} else {
cout<<" ";
}
}
cout<<endl;
}
for(int i=1; i<=n; i++) {
cout<<"*";
}
return 0;
}
懂了不
点个关注
祝你做题愉快