【问题标题】:C: None-Recursive function into recursive function [closed]C:将非递归函数转换为递归函数[关闭]
【发布时间】:2023-04-05 20:15:02
【问题描述】:

我需要编写一个程序来计算从 0 到 n 的数字的平方。我知道如何使用迭代来做到这一点,但是如何使用递归来重写注释函数?我觉得这是一项简单的任务,我应该毫无问题地处理它,但是出了点问题。

#include <stdio.h>
#include<conio.h>

int main()
{
    int x=0, n,m;
    printf("Enter last integer ");
    scanf_s("%d\n", &n);
    while (x < n) /* How to rewrite this function using recursion?*/
    {
        printf("\n%d\n", x*x);
        x++;
    }
    _getch();
    return 0;
}

【问题讨论】:

  • "但是出了点问题" --- 什么?请展示你的努力。实际上,您是在向我们展示可以运行的代码,但在一些 other 代码中请求调试帮助。
  • 指定你必须应用递归的部分。计算正方形和/或打印从 0 到 n 的正方形。

标签: c recursion iteration


【解决方案1】:

您可以使用以下功能:

void function(int i, int n)
{
     if(i < n)
     {
          printf("\n%d\n", i*i);
          function(i + 1, n);
     }
     else
          return;
}

然后拨打function(0, n);

【讨论】:

  • 我忘了说我不能使用乘法,但我想我现在可以自己解决这个问题。谢谢你的帮助。
【解决方案2】:

解决办法是:

void ipow(int x)
{
    if (x>1)
        ipow(x-1);
    printf ("%d\n",x*x);
}

注意:在递归调用之前或之后放置 print 语句会以递减或递增的顺序打印结果。

【讨论】:

    【解决方案3】:

    我正在重新连接你的程序以满足递归方式。

    #include <stdio.h>
    #include<conio.h>
    
    void square(int x, int n)
    {
     if(x < n)
     {
          printf("\n%d\n", x*x);
          function(++x, n);
     }
     else
          return;
    }
    
    
    int main()
    {
     int x=0, n,m;
     printf("Enter last integer ");
     scanf_s("%d\n", &n);
     square(x,n);
       _getch();
     return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2021-07-25
      相关资源
      最近更新 更多