递归如何在c langauge中起作用? [英] how recursion works in c langauge?

查看:62
本文介绍了递归如何在c langauge中起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

递归如何在c中起作用?解释详细示例。

How recursion works in c? explaination with detail example.

推荐答案

您最好学习如何执行简单的Google搜索 [ ^ ]。
You''d better learn how to perform a simple Google search[^].


和其他任何编程语言一样。



因为这很像你的作业,我不会给你任何密码!但它很简单:

以一个因子为例(它实际上不是你用递归实现的东西,因为它有更好的方法来解决它,但它很容易解释和理解)



因子(N)= N *因子(N -1),而N> 1



因此,Factorial的定义使用Foactorial定义自身 - 它将自身称为其定义的一部分。它使用递归来定义自己。这就是为什么有些字典定义 [ ^ ]递归仅由以下单词组成:请参阅递归



所以当你编写一个函数来计算一个阶乘,你可以这样写:

Just the same way it does in any other programming language.

Since this smells heavily of your homework, I''ll give you no code! But it''s pretty simple:
Take a factorial as an example (it''s not actually something you would implement with recursion becasu ethere are much better ways to work it out, but it is easy to explain and understand).

Factorial(N) = N * Factorial(N -1) while N > 1

So the definition of a Factorial uses a Foactorial to define itself - it refers to itself as part of it''s definition. It uses recursion to define itself. That''s why some dictionary definitions[^] of recursion consist of just the words: "see Recursion"

So when you write a function to calculate a factorial, you can write it as this:
int Factorial(int N)



1)如果N <= 1,则返回1

2)返回N * Factorial(N - 1)


1) If N <= 1, return 1
2) return N * Factorial(N - 1)


#include<stdio.h>
int fact(int);
int main(){
  int num,f;
  printf("\nEnter a number: ");
  scanf("%d",&num);
  f=fact(num);
  printf("\nFactorial of %d is: %d",num,f);
  return 0;
}

int fact(int n){
   if(n==1)
       return 1;
   else
       return(n*fact(n-1));
 }









阶乘是最好的和简单的递归的例子....





factorial is a best and simple example for recursion....


这篇关于递归如何在c langauge中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆