简体   繁体   English

简单的递归问题

[英]Simple recursion question

This code gives every step-result of computing factorial of given number but I want only the final.这段代码给出了计算给定数字的阶乘的每一步结果,但我只想要最终的结果。

#include <stdio.h>

long int factorial(int n) {
  if (n <= 1)
    return(1);
  else
    n = n * factorial(n - 1);
  printf("%d\n", n);
  return(n);
}

main() {
  int n;
  printf("Enter n: ");
  scanf("%d", &n);

  //function call
  factorial(n);
  return 0;
}

How about this?这个怎么样?

int final;

final = factorial(n);
printf("%d! = %d\n", n, final);

And stop using printf in the factorial function.并停止在factorial function 中使用printf

So don't use printf inside your recursive function but only print the return value inside main() .所以不要在递归 function 中使用printf ,而只在main()中打印返回值。

Avoid using printf();避免使用printf(); in the recursive function.在递归 function 中。

Writing printf();编写printf(); inside the recursive function is printing the value everytime.在递归 function 内部每次都在打印该值。 So, just place it outside the function.因此,只需将其放在 function 之外。

Like this:像这样:

#include <stdio.h>

long int factorial(int n) {
    if (n<=1)
        return(1);
    else
        n=n*factorial(n-1);
    return(n);
}

main() {
    int n,f;
    printf("Enter n: ");
    scanf("%d",&n);
    //function call
    f = factorial(n);
    printf("Factorial of %d is %d\n",n,f);     // See the change here ....
    return 0;
}
long int factorial(int n){
     if(n<=1)
        return 1;
     return n*factorial(n-1);
}

Use this,用这个,

long int factorial(int n) {    
    if (n<=1)      
        return(1);  
    else    
        n=n*factorial(n-1);  
    //printf("%d\n",n);    
    return(n);
} 

main(){ 
    int n, result;  
    printf("Enter n: ");  
    scanf("%d",&n);
    //function call  
    result=factorial(n);
    printf("%d\n",result);    

    return 0;
}

[This answer was originally edited into the question by the original poster, replacing the incorrect code. [此答案最初由原始发布者编辑为问题,替换了错误的代码。 The question has been restored and the solution re-posted in this community wiki answer.]该问题已恢复,并且在此社区 wiki 答案中重新发布了解决方案。]


Reworked the code and now it looks like this.重新编写代码,现在看起来像这样。 Thanks for the suggestions.感谢您的建议。

#include <stdio.h>
long int factorial(int n)
{
    if (n<=1)
        return(1);
    else
        n=n*factorial(n-1);
    return(n);
}
int final(int n)
{
    int result = factorial(n);
    printf("%d! = %d\n", n, result);
    return 0;
}

main()
{
    int n;
    printf("Enter n: ");
    scanf("%d",&n);
    //function call
    final(n);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM