【问题描述】
分别采用递归、非递归方法实现输出数字金字塔。需要编程过程
关于#c++#的问题:【问题描述】分别采用递归、非递归方法实现输出数字金字塔
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- m0_57781768 2022-12-29 23:44关注
当然!以下是如何使用递归和非递归方法在 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
我希望这有帮助!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 基于卷积神经网络的声纹识别
- ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
- ¥100 为什么这个恒流源电路不能恒流?
- ¥15 有偿求跨组件数据流路径图
- ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
- ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
- ¥15 CSAPPattacklab
- ¥15 一直显示正在等待HID—ISP
- ¥15 Python turtle 画图
- ¥15 stm32开发clion时遇到的编译问题