简体   繁体   English

为什么我的递归没有运行变量?

[英]Why is my recursion not running with variables?

I wanted to ask why the first code functions and the second is not?我想问为什么第一个代码起作用而第二个不起作用? Both are recursions and should calculate the binomial coefficient when going up the pascal triangel.两者都是递归,应该在上升帕斯卡三角形时计算二项式系数。 Thanks.谢谢。

#include <stdio.h>
#include <stdlib.h>
int rekurs(int n, int k)
{   if((k==0)||(n==0)||(n==k))
    {
        return 1;
    }

    else{ 
      return rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}
int main(int argc, const char *argv[])
{
    int spalte = atoi(argv[1]);
    int zeile= atoi(argv[2]);
    printf("%d,%d",zahlen,rekurs(spalte,zeile));
    return 0;
}



#include <stdio.h>
#include <stdlib.h>
int rekurs(int n, int k)
{ int ergebnis;
  if((k==0)||(n==0)||(n==k))
    {
        ergebnis = 1;
    }

    else{ 
      return ergebnis = rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}
int main(int argc, const char *argv[])
{
    int spalte = atoi(argv[1]);
    int zeile= atoi(argv[2]);
    printf("%d,%d",zahlen,rekurs(spalte,zeile));
    return 0;
}

The second recursive function returns nothing if the expression in the if statement evaluates to true如果 if 语句中的表达式计算结果为真,则第二个递归 function 不返回任何内容

int rekurs(int n, int k)
{ int ergebnis;
  if((k==0)||(n==0)||(n==k))
    {
        ergebnis = 1;
    }

    else{ 
      return ergebnis = rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}

At least you need to write至少你需要写

int rekurs(int n, int k)
{ int ergebnis;
  if((k==0)||(n==0)||(n==k))
    {
        ergebnis = 1;
        return ergebnis;
    }

    else{ 
      return ergebnis = rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}

though using the variable ergebnis is redundant.尽管使用变量ergebnis是多余的。

Also it seems the arguments of the functions must be non-negative values but the functions do not take this into account.此外,函数的 arguments 似乎必须是非负值,但函数没有考虑到这一点。

So it will be better to declare the function like所以最好像这样声明 function

unsigned long long int rekurs( unsigned int n, unsigned int k )
{   if((k==0)||(n==0)||(n==k))
    {
        return 1;
    }

    else{ 
      return rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}

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

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