aardvarkk 的解决方案是最好的,但如果你想要一个只有一个功能的版本:
#include <iostream>
using namespace std;
void recursivePrintLettersTriangle (char start, char end, char current, int space, bool newLine) {
// Print spaces
if ((current + space) < end) {
std::cout << ' ';
recursivePrintLettersTriangle(start, end, current, space + 1, newLine);
// Print letters
} else if (start <= current) {
std::cout << start;
if (start < current) {
recursivePrintLettersTriangle(start + 1, end, current, space, false);
std::cout << start;
}
// Go to next line
if (newLine) {
std::cout << std::endl;
if (current < end) {
recursivePrintLettersTriangle(start, end, current + 1, 0, newLine);
}
}
}
}
void showLettersTriangle (char start, char end) {
recursivePrintLettersTriangle(start, end, start, 0, true);
}
int main() {
showLettersTriangle('a', 'g');
return 0;
}