空心正方形

问题 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;
}
懂了不

点个关注

祝你做题愉快

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值