【发布时间】:2018-11-28 12:51:56
【问题描述】:
预警,这是家庭作业。 我应该创建一个递归函数,但我做错了。当我输入 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);
}
}
感谢大家的帮助,从你们的cmets和建议中学到了很多。 我相信我能够让它工作https://pastebin.com/v9cZHvy0
【问题讨论】:
-
每个递归函数都有 (1) 退出条件和 (2) 递归调用。您没有提供退出条件。此外,您需要
scanf("%d", &n)(注意'&')并且您必须验证return,例如if (scanf("%d", &n) != 1) { /* handle error */ }。您对f(n);的调用不是// Pointer for f,它只是一个函数调用(在那里没有什么意义)。想想你的递归调用集必须如何退出。由于(x-3)+(x+5)的计算量会增加,所以x <= 0不能成为退出条件。 -
@DavidC.Rankin:退出条件为
x <= 0。看来你可能错过了f(x-3)调用f而(x+5)没有。 -
是的,我读的是
f (x-3 + x + 5)。