2013-04-06 76 views
-5

我一直在阅读一本编程手册,它希望我编写一个程序,列出前10个阶乘数字的表格。我一直在尝试过去45分钟,但无法提出解决方案。请帮忙!我很确定该程序涉及使用循环。如何在目标c中编写阶乘函数

回答

3

计算阶乘的最简单方法是使用递归函数或简单的循环,如下所示。我会让你知道如何在表格中列出这些信息,因为有很多方法可以对这只猫进行皮肤处理。

函数的头文件声明:

-(int)factorialRecursive:(int)operand; 
-(int)factorialLoop:(int)operand; 

实现文件的函数声明:

-(int)factorialRecursive:(int)operand 
{ 
    if(operand == 1 || operand == 0) { 
     return(1); 
    } else if(operand < 0) { 
     return(-1); 
    } 

    return(operand * [self factorialRecursive:operand-1]); 
} 

-(int)factorialLoop:(int)operand 
{ 

    if(operand == 1 || operand == 0) { 
     return(1); 
    } else if(operand < 0) { 
     return(-1); 
    } 

    int factorial = 1; 
    for(int i = operand; i > 1; i--) { 
     factorial *= i; 
    } 

    return(factorial); 

} 

调用示例:

int factNumber = 10; 
NSLog(@"%d! = %d",factNumber,[self factorialRecursive:factNumber]); 
NSLog(@"%d! = %d",factNumber,[self factorialLoop:factNumber]); 
+2

递归?为什么?请使用简单的循环。 – rmaddy 2013-04-06 15:26:07

+0

那里没有参数。当n很大时,迭代循环会更快,因为循环中的开销远小于递归方法调用的开销。我只是试图用他在要求方面提供的少量信息来回答他的问题。 ;)我会更新我的答案来反映这一点。 – 2013-04-06 15:30:11

+0

OP确实提到了循环,而不是递归。 – rmaddy 2013-04-06 15:30:56