c - 我想输出 1 3 4 5 7 9 但我几乎卡在这里

标签 c function recursion parameters parameter-passing

我已经尝试了两个小时,但找不到答案。 如果有人可以帮助我,我将非常感激。

#include <stdio.h>

void somefunction(const int[], int);

int main() {
  int a[] = { 1, 3, 4, 5, 7, 9, 11 };
  somefunction(a, 5);
  return 0;
}

void somefunction(const int b[], int c) {
  if (c > 0) {
    somefunction(b[], c - 1);
    printf("%d ", b[c]);
  }
}

最佳答案

if (c > 0) 是问题所在。你需要做到 if (c >= 0) 打印 a[0]1 的值。

此外,在 somefunction 内递归调用 somefunction 时的第一个参数需要省略 []

作为附加提示,要打印 a[6]11 的值,您需要更改

somefunction(a,5);

main()中到

somefunction(a,6);
<小时/>

恢复代码是这样的:

#include <stdio.h>

void somefunction(const int[], int);

int main() {
  int a[] = { 1, 3, 4, 5, 7, 9, 11 };
  somefunction(a,6);
  return 0;
}

void somefunction(const int b[], int c) {
  if (c >= 0) {
    somefunction(b, c - 1);
    printf("%d ", b[c]);
  }
}

输出:

1 3 4 5 7 9 11

关于c - 我想输出 1 3 4 5 7 9 但我几乎卡在这里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60023865/

相关文章:

javascript - 如何为此按钮添加 `onclick` 事件

c++ - 使用此函数查找数组的长度

python - Django 查找图中两个顶点之间的路径

c - 在结构体中使用双指针

c++ - 错误代码 1024 tftp 服务器

我们可以将 bzip2 block 大小减少到 100KB 以下吗?

javascript - 在下划线模板中使用函数

python - 如何理解DFS中尾递归和for循环的关系

javascript - js setTimeout递归返回-继续

c - 如何检查 C 中的特定端口是否可以访问远程主机?