2013-04-06 81 views
-5

我一直在閱讀一本編程手冊,它希望我編寫一個程序,列出前10個階乘數字的表格。我一直在嘗試過去45分鐘,但無法提出解決方案。請幫忙!我很確定該程序涉及使用循環。如何在目標c中編寫階乘函數

回答

3

計算階乘的最簡單方法是使用遞歸函數或簡單的循環,如下所示。我會讓你知道如何在表格中列出這些信息,因爲有很多方法可以對這隻貓進行皮膚處理。

函數的頭文件聲明:

-(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]); 
+2

遞歸?爲什麼?請使用簡單的循環。 – rmaddy 2013-04-06 15:26:07

+0

那裏沒有參數。當n很大時,迭代循環會更快,因爲循環中的開銷遠小於遞歸方法調用的開銷。我只是試圖用他在要求方面提供的少量信息來回答他的問題。 ;)我會更新我的答案來反映這一點。 – 2013-04-06 15:30:11

+0

OP確實提到了循環,而不是遞歸。 – rmaddy 2013-04-06 15:30:56