2017-04-03 41 views
0

在下面的问题中,我在任何一个编译器上都尝试了超出时间限制的消息(尽管它们都是在线编译器)。问题应该是什么?为什么它显示超出了时间限制?

#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; 
} 
+0

这非常依赖于您的输入。 –

+0

在您的机器上安装独立编译器。这不是编译期,而是运行时问题。您的程序编译良好,但运行很长时间,这取决于您的输入。 – ForceBru

回答

4

问题是,你的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; 
} 
+0

谢谢....但即使做了你告诉我没有得到所需的输出。尽管时间限制消息已经消失 – user1712

+0

@kabby你得到的是什么而不是所需的输出? – JeremyP

+1

@kabby请记住,与正常的32位'int'最大的因子就可以计算出当我给5作为输入12 – JeremyP

1

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

假设你计算一个数x的阶乘,这应该是正确的事实函数。

int fact(int x) 
{ 
    if(x!=1) 
     return x*fact(x-1); 
    return 1; 
} 
0
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; 
} 
相关问题