C:None-Recursive函数变为递归函数

标签 c recursion iteration

我需要编写一个程序来计算从 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;
}

最佳答案

您可以使用以下功能:

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

然后调用function(0, n);

关于C:None-Recursive函数变为递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49598170/

相关文章:

recursion - 使用 FTP 将文件递归地 PUT 到远程服务器

python - 迭代时修改列表

c++ - 遍历流缓冲区时如何摆脱 no "matching function call error"?

c - 从C中的链表中删除一些元素

python - 如何限制同时递归调用2个函数的次数? - Python

javascript - 无限循环不起作用

function - 和谁谈论非递归阿克曼函数?

c - Makefile:使所有 '.c' 文件依赖于同名头文件的有效方法?

c - 在 C 中反转字符串

c - 我不断收到编译错误预期 ‘;’ 、标识符或 ‘(’ before ‘void’ void *runner(void *param)