2012-04-29 109 views
-5
#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; 
} 

这段代码有什么问题?我是新的客观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) 

并在执行结果EXC_BAD_ACESS处卡在行+(int)阶乘:(int)n处。

感谢

+3

什么是编译器告诉你? – huon 2012-04-29 07:00:40

+1

你告诉我们问题是什么,我们会帮你解决的。 :) – whooops 2012-04-29 07:08:32

回答

1

我不熟悉ObjC,但行:

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

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

+0

谢谢..愚蠢的错误.. – 2012-04-29 08:21:50

+0

应该是这样.. ..返回n * [自析阶:n-1]; – 2012-04-29 08:23:43

+0

顺便说一句,如果你改变实现以使用tail call,它会更节省空间。 – Greg 2012-04-30 09:09:25

2

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

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

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

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"