我的递归函数只计算偶数的一半

Ale*_*tos 0 c recursion

#include <stdio.h>

int succ(int x) {
  return x+1;
}

int pred(int x) {
  return x-1;
}

int is_zero(int x) {
  return x == 0;
}

int is_pos(int x) {
  return x >= 0;
}

int half(int x, int y) {
    return is_zero(y) ? x: half(pred(x), pred(pred(y)));
}

int half1(int x) {
    return half(x,x);
}

int main() {
    int x;
    scanf("%d", &x);
    int z = half1(x);
    printf("%d\n", z);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是我在大学收到的第一个练习,我遇到了一点困难。我只能使用函数 succ,pred,is_zero,is_pos 来创建一个计算一半数字的递归函数,而不能使用 if 或 while 。我编写了这段代码,但它只适用于偶数,例如输入=30 输出=15,但如果输入=17,它将不会返回输出。有小费吗?

Chr*_*ris 5

当你尝试时会发生什么half1(17)

half1(17)
half(17, 17)
half(pred(17), pred(pred(17)))
half(16, pred(16))
half(16, 15)
half(15, 13)
half(14, 11)
half(13, 9)
half(12, 7)
half(11, 5)
half(10, 3)
half(9, 1)
half(8, -1)
half(7, -3)
...
Run Code Online (Sandbox Code Playgroud)

y在这种情况下永远不会等于0,因此递归永远不会结束。

您想要检查是否y为负(正)或等于零。

int half(int x, int y) {
    return !is_pos(y) || is_zero(y) ? x : half(pred(x), pred(pred(y)));
}
Run Code Online (Sandbox Code Playgroud)

现在,递归将以 和half(8, -1)返回8