2012-04-29 4 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の@implementationでline +(int)factorial:(int)nにスタックしています。

おかげ

+3

? – huon

+1

あなたは問題が何であるか教えてください。問題を解決するのに役立ちます。 :) – whooops

答えて

1

私はにObjCに慣れていないけど、ライン:

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

は私のため不審に見えます。これは、n!= 0の場合、無限の再帰と面スタックのオーバーフローが発生することを意味します。

+0

ありがとう..愚かな間違い.. –

+0

はこのようにする必要があります..返すn * [自己階乗:n - 1]; –

+0

BTWでは、テールコールを使用するように実装を変更すると、スペース効率が向上します。 – Greg

2

factorial:nを計算しますが、関数内ではfactorial:nの結果を使用します。あなたが最初のものはINFINITを行います

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

する

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

をあなたのコードを変更する必要が return n*[self factorial:n-1];

1

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

変更にEループ例えば

:コンパイラはあなたに何を言っている

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