我没有主意了。我以前只处理递归函数的整数, 所以程序输出应该是:
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
最佳答案
由于字符串是 C 语言中的字符数组/指针(具有“NUL
字符标记结束”约定),因此获得“字符串作为值”的预期递归行为的方法是包装一个字符结构体中的数组。像这样:
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);
}
我没有尝试在这里解决您的编程问题,只是说明如何将字符串作为递归函数中的值进行处理。它对于函数参数的工作方式相同,而不仅仅是结果。
关于c - 递归函数返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33112344/