-6

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

4

1 回答 1

4

计算阶乘的最简单方法是使用递归函数或简单循环,如下所示。我将由您来决定如何在表格中列出信息,因为有很多方法可以给猫剥皮。

头文件函数声明:

-(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]);
于 2013-04-06T15:21:29.417 回答