递归因子

时间:2012-04-29 06:57:09

标签: objective-c

#import <Foundation/Foundation.h>

@interface Factorial : NSObject 
+(int) factorial:(int) n;
@end

@implementation Factorial

+(int) factorial:(int)n
{
    if (n==0) {
        return 1;
    }
    else
    {
        return [self factorial:n]*[self factorial:n-1];
    }
}

@end

int main (int argc, const char * argv[])
{
    int i = [Factorial factorial:5];
    NSLog(@"%d", i);
    return 0;
}

这段代码有什么问题?我是Objective-c的新手(我来自c背景) 或者,我对目标c?

(Compiler generating ..)
GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug  8 20:32:45 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys002
sharedlibrary apply-load-rules all
[Switching to process 1413 thread 0x0]
warning: Unable to restore previously selected frame.
(gdb) 

并且在@implementation的行+ +(int)factorial:(int)n中卡住了EXC_BAD_ACESS。

谢谢

3 个答案:

答案 0 :(得分:2)

您想要计算factorial:n,但在您的函数中使用factorial:n的结果。

变化: return [self factorial:n]*[self factorial:n-1];

于: return n*[self factorial:n-1];

答案 1 :(得分:1)

我不熟悉ObjC,但行:

+(int) factorial:(int)n
    //...
    return [self factorial:n]*[self factorial:n-1];
    //                      ^

看起来对我很怀疑。这意味着对于n!= 0,您将获得无限的递归和面堆栈溢出: - )

答案 2 :(得分:1)

您必须更改代码

return n*[self factorial:n-1];

return  n* (n != 1 ? [self factorial:n-1] : 1);

第一个将进行无限循环

例如:

int factorial = [self factorial:3];
NSLog(@"factorial 3 >> %i",factorial); the result is "factorial 3 >> 6"
相关问题