简体   繁体   English

为什么这个 c 程序无法编译阶乘

[英]why this c program can't compile factorial

#include <stdio.h>

int FAC(int a)
{
    if (a >= 1, a--)
    {
        return a + 1 * a;
        FAC(a);
    }
}

int main() 
{
    int a = 0;
    int ret = 0;
    scanf("%d", &a);
    ret = FAC(a);
    printf("%d\n", ret);
}

if I input 5 the outcome is 8如果我输入5结果是8

But in the first function should't it be但是在第一个 function 不应该是

5>=1 5-1 return 5*4 4>=1... 5>=1 5-1 返回 5*4 4>=1...

First of all, you're returning a value before you're using recursion.首先,您在使用递归之前返回一个值。 The return keyword takes effect immediately, so all statements following this won't be executed. return关键字立即生效,因此后面的所有语句都不会被执行。

Also, your factorial function does not actually calculate the factorial of a .此外,您的阶乘 function 实际上并没有计算a的阶乘。

Examples for factorial functions:阶乘函数的示例:

Recursive递归的

int factorial(int n) {
  if(n > 0) {
    return n * factorial(n - 1); // n! = n * (n-1) * (n-2) * ... * 1
  } else {
    return 1;
  }
}

Iterative迭代

// Does exactly the same, just an iterative function
int factorial(int n) {
  int fac = 1;
  for(; n > 0; n--) {
    fac *= n;
  }
  return fac;
}
#include <stdio.h>  

int FAC(int a)
{
    if (a < 0) {
        return -1;
    } else {
        if (a == 0) {
            return 1;
        } else {
            return (a * FAC(a-1));
        }
    }
} 

int main()  
{  
  int a = 0;  
  int ret = 0;  
  scanf("%d", &a);   
  ret = FAC(a);
  if (ret == -1) {
    printf("%s\n", "Input was a negative integer.");
  } else {    
    printf("%d\n", ret); 
  }
}  

Your factorial function ( FAC ) should ideally be something like:您的阶乘 function ( FAC )理想情况下应该是这样的:

unsigned int FAC(unsigned int a)
{
    // base condition - break out of recursion
    if (a <= 1)
        return 1;

    return a * FAC(a - 1);
}

unsigned int restricts range of argument to be in [0, UINT_MAX] . unsigned int将参数范围限制在[0, UINT_MAX]中。

Do note that FAC returns a unsigned int , so you may be able to provide argument value up to 12, else there will be an overflow and you can see weird output.请注意FAC返回一个unsigned int ,因此您可以提供最大为 12 的参数值,否则会出现溢出,您会看到奇怪的 output。

BTW, UINT_MAX is defined in limits.h顺便说一句, UINT_MAXlimits.h中定义

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

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