【问题标题】:Function to calculate max value of int not returning desired result计算 int 最大值的函数不返回所需结果
【发布时间】:2016-02-12 13:23:57
【问题描述】:

我刚开始学习 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 语句,所以我“确定”我只返回一次并且值是正确的。

请指出哪里出了问题。

【问题讨论】:

  • 确实知道整数溢出是未定义的,对吧?
  • 好吧,看看 C 标准。 C11 标准草案 n1570(在网络上公开提供):6.5 Expressions, Section 5 If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.
  • 好的,非常感谢

标签: c


【解决方案1】:

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

所以最后一行应该是:

return max_int_helper(prev_i);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2017-10-26
    • 2021-12-12
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多