为什么显示超时?

Why it is showing time limit exceeded?

在下面的问题中,无论我尝试使用哪个编译器(尽管它们都是在线编译器),我都收到超过时间限制的消息。应该是什么问题?

#include <stdio.h>
int fact(int);
int main(void)
{
    int num,res;
    printf("enter any number");
    scanf("%d",&num);
    res=fact(num);
    printf("%d",res);
    return 0;
}
int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1));
    return ans;
}

问题是您的 fact 函数从未停止,因为 while 循环永远不会结束。

int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1)); //X is never changed!
    return ans;
}

可能你想要这个:

int fact(int x)
{
    int ans = 1; //Set default value for return
    if(x!=1) //Go recursive only if X != 1
        ans=(x*fact(x-1));
    return ans;
}

这是因为你的事实函数进入了无限循环。

假设您正在计算数字 x 的阶乘,这应该是正确的事实函数。

int fact(int x)
{
    if(x!=1)
        return x*fact(x-1);
    return 1;
}
int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1));
    return ans;
}

这是一个无限循环。这就是为什么您在超过时间限制时收到错误的原因。 将循环替换为 if 条件:

int fact(int x)
{
    int ans = 1;
    if(x!=1)
        ans=(x*fact(x-1));
    return ans;
}