优化这段代码void PrintChar(char ch){ putchar(ch);}void PrintHollowChar(char ch){ putchar(' ');}void ShowHollow(int number, char symbol, int hollow){ if (number <= 0) { return; } if (number == 1) { PrintChar(symbol); return; } if (hollow) { PrintChar(symbol); for (int i = 0; i < number - 2; i++) { PrintHollowChar(symbol); } PrintChar(symbol); } else { PrintChar(symbol); ShowHollow(number - 1, symbol, hollow); }}
时间: 2024-03-22 18:39:28 浏览: 94
好的,以下是对应的优化后的代码:
```c++
#include<iostream>
using namespace std;
void PrintChar(char ch);
void PrintHollowChar(char ch);
void ShowHollow(int number, char symbol, int hollow);
int main() {
int n, h;
char s;
cin >> n >> s >> h;
ShowHollow(n, s, h);
cout << endl;
return 0;
}
void PrintChar(char ch) {
putchar(ch);
}
void PrintHollowChar(char ch) {
putchar(' ');
}
void ShowHollow(int number, char symbol, int hollow) {
if (number <= 0) {
return;
}
if (number == 1) {
PrintChar(symbol);
return;
}
if (hollow) {
PrintChar(symbol);
for (int i = 0; i < number - 2; i++) {
PrintHollowChar(symbol);
}
PrintChar(symbol);
}
else {
PrintChar(symbol);
ShowHollow(number - 1, symbol, hollow);
}
}
```
优化后的代码将字符输出的操作封装成了两个函数PrintChar和PrintHollowChar,这样可以提高代码的可读性和可维护性。
阅读全文