递归函数方程

时间:2018-11-28 04:03:40

标签: c recursion

预警,这是一项家庭作业。 我应该创建一个递归函数,但是我做错了。当我输入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

能够使它正常工作

2 个答案:

答案 0 :(得分:2)

据我所知,第一个是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) );
}

未成年人-以下声明实际上无用

//Pointer for f
  f(n);

答案 1 :(得分:0)

作为生活中的学生,我一直乐于帮助一位学者:

您的代码中应注意一些错误:

  1. body { background: #077054; color: #315f52; } .header { text-align: center; } .header a { text-decoration: none; color: #99fa99; font-size: 20px; font-weight:normal; font-family: "latoregular"; } .header span { color: #b6d8cf; font-size: 26px; text-transform: uppercase; font-family: 'nixie_oneregular'; } .listHorizontal { color: #b6d8cf; font-size:30px; text-transform: uppercase; list-style: none; display:inline-block; } 没有返回语句,即使它期望一个整数也是如此。我假设您希望返回程序的结果(请参阅问题3)。

  2. 您执行两次f(n)。首先在第12行,然后在第16行。int f(int x)实际上执行F(n)以便接收其返回值以与%d格式说明符关联。

  3. 您尚未将printf("f(x) is %d\n", f(n));x+3分配给任何整数。这些语句不会保存您需要返回的f(x)的返回值。

此链接可能对您有帮助:

https://www.geeksforgeeks.org/c-function-argument-return-values/

特别注意如何捕获函数的输出。

希望这会有所帮助(祝您学习成功!)

相关问题