c - 递归函数方程

标签 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

最佳答案

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

相关文章:

c - 反转C样式字符串-运行时错误

c - 使用指向从函数返回的结构的指针

c - 当 double 值超出 char 范围时,C 中的 Double 到 char 转换规则

C - 生产者/消费者死锁问题

algorithm - 左递归语法识别

c - 实现一个函数以递归方式返回有效的获胜条件 - C

java - 递归地构建链接对象的列表

在 c 中创建自己的 malloc 函数

language-agnostic - "Necessary"命令式语言中递归的使用

python - 按字母顺序查找最长的子串