-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;
}

这段代码有什么问题??我是objective-c的新手(我来自c背景)或者,我对objective 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导致EXC_BAD_ACESS处卡在+(int)阶乘:(int)n行。

谢谢

4

3 回答 3

2

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

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

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

于 2012-12-10T07:44:42.220 回答
1

我不熟悉 ObjC,但行:

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

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

于 2012-04-29T07:15:03.103 回答
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"
于 2016-07-23T12:58:39.657 回答