1036 跟奥巴马一起编程 (15 point(s))

#include <bits/stdc++.h>
using namespace std;

int main() {
	int n;
	char c;
	// 读取边长n 和字符c
	cin >> n >> c;
	
	// 行数是列数的一半 (四舍五入
	int line = (n & 1 ? n / 2 + 1 : n / 2);
	
	// 减去首尾行
	line -= 2; 
	
	// 第一行 
	for(int i = 0; i < n; i++)
		cout << c;
	cout << endl; 
	
	for(int i = 0; i < line; i++){
		// 第一列字符 
		cout << c;
		// 中间字符 减去首尾列 
		for(int j = 0; j < n - 2; j++)
			cout << ' ';
		
		// 最后一列字符 
		cout << c;
		
		cout << endl; 
	}
	
	// 最后一行 
	for(int i = 0; i < n; i++)
		cout << c;
}

这里代码里面的四舍五入是照着算法笔记里面,奇数进一偶数不变。看别人的代码还有另一种方式,直接对整数 +1 ,如果原来是偶数的话,比如10, 10 / 2 = 5, (10 + 1) / 2 = 5.5 = 5。而奇数 11 / 2 = 5, (11 + 1) / 2 = 6。这样就不需要判断了。


if (j == 0 || j == N - 1)
	cout << C;
else
	cout << " ";

参考代码里面还有一种写法。之前的想法是将不同的部分拆开,用循环来统一输出。而如果要把代码精简的话,参考里面用选择判断的方式,通过判断不同的行或者列,来根据其特征来选择到底是输出空格还是字符,或者是多换一行还是其他。

参考代码

posted on 2021-08-31 09:33  Atl212  阅读(34)  评论(0)    收藏  举报

导航