【问题描述】
分别采用递归、非递归方法实现输出数字金字塔。需要编程过程
当然!以下是如何使用递归和非递归方法在 C++ 中实现数字金字塔的简要说明:
使用递归方法:
定义一个以整数 n 作为输入参数并返回 void 的函数。此函数将用于打印一行数字金字塔。
在函数中,基本情况:如果 n 为 0,则返回而不打印任何内容。
否则,打印 n,后跟一个空格。
以 n-1 作为输入参数递归调用该函数。
递归调用返回后,再次打印 n,后跟一个空格。
从函数返回。
要打印整个数字金字塔,您可以在循环中调用此函数,从 n 开始并在每次迭代中减少 n 的值。
#include <iostream>
void printRow(int n) {
// base case: if n is 0, return without printing anything
if (n == 0) return;
// print n, followed by a space
std::cout << n << " ";
// call the function recursively with n-1 as the input parameter
printRow(n-1);
// after the recursive call returns, print n again, followed by a space
std::cout << n << " ";
}
int main() {
// print the digital pyramid for n = 4
for (int i = 4; i >= 1; i--) {
printRow(i);
std::cout << std::endl;
}
return 0;
}
使用非递归方法:
定义一个以整数 n 作为输入参数并返回 void 的函数。此函数将用于打印一行数字金字塔。
在函数中,使用循环从 1 迭代到 n。
在每次迭代中,打印循环变量,后跟一个空格。
循环完成后,使用另一个循环从 n-1 向下迭代到 1。
在每次迭代中,打印循环变量,后跟一个空格。
从函数返回。
要打印整个数字金字塔,您可以在循环中调用此函数,从 n 开始并在每次迭代中减少 n 的值。
#include <iostream>
void printRow(int n) {
// use a loop to iterate from 1 to n
for (int i = 1; i <= n; i++) {
// print the loop variable, followed by a space
std::cout << i << " ";
}
// use another loop to iterate from n-1 down to 1
for (int i = n-1; i >= 1; i--) {
// print the loop variable, followed by a space
std::cout << i << " ";
}
}
int main() {
// print the digital pyramid for n = 4
for (int i = 4; i >= 1; i--) {
printRow(i);
std::cout << std::endl;
}
return 0;
}
这两个程序都会输出以下数字金字塔:
4 3 2 1 2 3 4
3 2 1 2 3
2 1 2
1
我希望这有帮助!
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!