c - 计算 int 最大值的函数未返回所需结果

标签 c

我刚开始学习C。我试图通过计算找到一个int的最大值(实际上我试图通过相同的方法找到一个float的最大值,但我想测试它首先在 int 上)。 逻辑似乎没问题,但我的函数最后总是返回 0。

int max_int_helper(int base) 
{
  int prev_i, next_i, counter;
  counter = 1;
  prev_i = next_i = base + counter;

  // found max
  if (next_i < base) {
    printf("WE RETURN BASE %d\n", base);
    return base;
  } else {   
      while(prev_i <= next_i) 
      {
        prev_i = next_i;
        counter *= 2;
        next_i = base + counter;
      }
        max_int_helper(prev_i);
  }
}

我在主函数中这样调用它

printf("max int calculated: %d", max_int_helper(0));

但是当我运行这个东西时,我得到了这个:

我们返回基地 2147483647 计算的最大整数:0

我明确地放置了 printf 语句,这样我“确定”我只返回一次并且值是正确的。

请指出哪里出错了。

最佳答案

这是一个递归。您需要返回它的值。

所以最后一行应该是:

return max_int_helper(prev_i);

关于c - 计算 int 最大值的函数未返回所需结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33650790/

相关文章:

c - 如何在内存中保留一个非常大的数据集的多个副本?

c - 在 C 中使用带指针的模运算符

c - 八进制数字文字 : When? 为什么?曾经?

c - 用于读取 Char 类型输入时 scanf 的不可预测行为。

c - 将标准输入回显到标准输出

C 语言中的 CCAN JSON 序列化

C 指针变化无赋值

在 C 中比较字符串并打印存储的字符串

c - 字符串正在打印奇怪的字符 - lex 中的 c 代码

python - 当用C扩展Python时,如何用C动态构建复杂的结构?