预先警告,这是一项家庭作业。 我应该创建一个递归函数,但我做错了。当我输入 4 时,我应该从 f(x) 得到结果 16,但我得到 -2。我真的不明白我哪里出错了。我也不知道我应该在 main 还是 f 中打印我的结果。
编写一个程序,向用户查询一个整数值并使用递归
返回以下递归定义值的函数:
f(x) =x+3 if x <=0 f(x)=f(x-3)+(x+5) otherwise
我的尝试:
#include <stdio.h>
int f(int x); //Prototype to call to f
int main(void) {
int n; //number the user will input
//Ask user to input data an reads it
printf("Enter a whole number: ");
scanf("%d", &n);
//Pointer for f
f(n);
//Prints results
printf("\nn is %d\n", n);
printf("f(x) is %d\n", f(n));
return 0;
}
int f(int x) {
//Checks if equal to zero
if (x <= 0) {
x + 3;
}
//If not equal to zero then do this
else {
f(x - 3) + (x + 5);
}
}
谢谢大家的帮助,从你们的意见和建议中学到了很多。 我相信我能够让它工作 https://pastebin.com/v9cZHvy0
最佳答案
据我所知,第一个是scanf
scanf("%d", &n);
第二个是你的函数 f
没有返回任何东西,所以这个
int f(int x) {
//Checks if equal to zero
if (x <= 0)
{
return (x + 3);
}
return ( f(x-3) + (x+5) );
}
minor - 下面的语句实际上是无用的
//Pointer for f
f(n);
关于c - 递归函数方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53511943/