2015-10-13 278 views
0

我用完了想法。我只用來處理遞歸函數整數, 所以程序的輸出應該是:遞歸函數返回字符串

Please enter a number : 4 
a 
ab 
abc 
abcd 
abc 
ab 
a 

到目前爲止,這是我想出的唯一的事:

#include <stdio.h> 
char arr [] ; 
char*arr function(int count){ 
    char ch='a'; 
    if(count==1||count==count) 
    return ch; 
    return (ch +function(count--)); 
}//end method 

main(){ 
    function(4); 
}//end main 
+4

'if(count == 1 || count == count)'does not make any sense since'count == count' would always true。你的函數也說你返回一個'char *'但是'return ch;'表示你返回一個'char'。同樣''return(ch + function(count - ));'你試圖添加兩個'char'值,在C中會給你每個字符的整數編碼值(我相信ASCII)想要 – JackVanier

+0

遞歸真的是實現這種輸出的最佳方式嗎? –

+0

考慮一下C字符串只是一個指向'char'數組的指針。 *字符串*的結尾由零字節指定,但不一定在數組的實際末尾。考慮分配一個足夠大的工作數組,並讓遞歸函數就地修改和打印內容。 –

回答

0

由於字符串的字符數組/ C中的指針(帶有「NUL char marks end」約定),將「字符串作爲值」的預期遞歸行爲的方法是將字符數組包裝到結構中。就像這樣:

struct MyString { 
    char s[10]; 
}; 

現在你會做這樣的事情:

struct MyString f(int count, int index) 
{ 
    struct MyString result; 
    rslt.s[0] = 'a' + index; 
    rslt.s[1] = '\0'; 
    if (count == 1) { 
     return result; 
    } 
    strcat(result.s, f(--count, ++index).s); 
    return result; 
} 

int main() 
{ 
    f(4, 0); 
} 

我還沒有嘗試過在這裏解決您的編程問題,只是說明如何處理字符串作爲遞歸函數的值。它對函數參數的作用方式相同,而不僅僅是結果。