m0_75093936 2022-12-29 23:20 采纳率: 100%
浏览 29
已结题

关于#c++#的问题:【问题描述】分别采用递归、非递归方法实现输出数字金字塔

【问题描述】
分别采用递归、非递归方法实现输出数字金字塔。需要编程过程

  • 写回答

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 
    
    
    

    我希望这有帮助!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 12月30日
  • 已采纳回答 12月30日
  • 创建了问题 12月29日

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog