【问题标题】:Comparing integer variables for the largest within a range比较范围内最大值的整数变量
【发布时间】:2016-03-31 03:15:59
【问题描述】:

我无法理解为什么我的代码无法解决我正在尝试解决的问题。

问题: 给定 2 个正 int 值,返回 10..20 范围内的较大值,如果两者都不在该范围内,则返回 0。

我的代码:

public int max1020(int a, int b) {
  int max;

  if((a<10 || a>20) && (b<10 || b>20)) {
  max = 0;
  }

  if(Math.max(a,b) >= 10 && Math.max(a,b) <= 20) {
  max = Math.max(a,b);
  } else {
  max = Math.min(a,b);
  }

  return max;
}

除了 a = 9 和 b = 21 时,每个数字都有效,我只是不明白。我哪里做错了?

【问题讨论】:

  • 使用调试器单步调试您的代码。
  • 返回 0 而不是将 max 设置为 0
  • 非常感谢大家的帮助。我知道我现在哪里出错了。

标签: java int max min


【解决方案1】:

你没有返回 0 .. 永远......所以.. 9 小于 10.. 并且 b 大于 20 所以返回 0。我认为你得到 9 是因为当两个数字都在界限。

公共 int max1020(int a, int b) { 最大整数;

      if((a<10 || a>20) && (b<10 || b>20)) {
      **>> return 0;**
      }

      if(Math.max(a,b) >= 10 && Math.max(a,b) <= 20) {
      max = Math.max(a,b);
      } else {
      max = Math.min(a,b);
      }

      return max;
    }

【讨论】:

    【解决方案2】:

    你的代码说 如果 a && b 不在 10 或 20 max = 0 之间。

    然后它继续计算哪个是最大值,哪个是最小值,无论数字是多少。

    如果 a&&b 不在 10 或 20 之间,则应立即返回 0。

    例如。

    public int max1020(int a, int b) {
      int max;
    
    if((a<10 || a>20) && (b<10 || b>20)) {
        return 0;
    }
    
    if(Math.max(a,b) >= 10 && Math.max(a,b) <= 20) {
        max = Math.max(a,b);
    } else {
     max = Math.min(a,b);
    }
    
    return max;
    }
    

    【讨论】:

    • 你的 else 语句永远不会到达。
    【解决方案3】:

    编辑了原始答案,因为我监督了一些案例。
    以下内容应该适合您的喜好

    static int max1020(int a, int b) {
        int max = 0;
        if ((a < 10 || a > 20) && (b < 10 || b > 20)) {
            //If neither fall between 10 and 20, return immediately.
            return max;
        }
        if (Math.max(a, b) >= 10 && Math.max(a, b) <= 20) {
            //If both fall between 10 and 20, return the larger value.
            max = Math.max(a, b);
        } else if ((a >= 10) && (a <= 20)) {
            //If both didn't fall between 10 and 20, check if it was a.
            max = a;
        } else {
            //If a didn't fall between 10 and 20, then it must be b.
            max = b;
        }
        return max;
    }
    

    【讨论】:

      【解决方案4】:

      这个呢?

      public int max1020(int a, int b) {
        int max = 0;
        if (10 <= a && a <= 20)
          max = a;
        if (10 <= b && b <= 20)
          max = Math.max(max, b);
        return max;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-03
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 2015-11-27
        • 2020-04-18
        相关资源
        最近更新 更多