【问题标题】:Stop a number at a certain range在一定范围内停止一个数字
【发布时间】:2014-05-01 11:05:04
【问题描述】:

基本问题,但我似乎无法解决它:

我有一个旋转的东西,我想在某个范围内停止它。

所以如果旋转(双精度)在一定范围内,我希望它返回 false。

例子

Rotation = 182, StopAt 180, Accuracy 2. 所以应该停止。

Rotation = 182, StopAt 180, Accuracy 1. 所以不应该停止。

目前我有:

/**
 *
 * @return
 * number = 100, current = 105, accuracy = 10
 * Example
 * 105c / 100n = 1.05..
 * 10c / 100n = 0.1..
 */
public boolean stopAtRange(double number, double current, double accuracy)
{
    if(current / number) + accuracy)
    {
        return true;
    }
    return false;
}

【问题讨论】:

  • 你想在这里做什么:if(current / number) + accuracy)?
  • if 需要 boolean 值,而不是 doubleif (a+b>0) 之类的东西是正确的,但 if(a+b) 不是。
  • 您发布的代码甚至无法编译。准确度范围是百分比还是绝对值?
  • 我已经根据你的例子更新了我的答案,见下文。

标签: java math rotation


【解决方案1】:

在 Java 中 if 只接受布尔值,整数值不会转换为布尔值。

要达到你想要的,你的方法应该是这样的

public boolean stopAtRange(double number, double current, double accuracy)
{
    if( Math.abs(current - number) <= accuracy)
    {
        return true;
    }
    return false;
}

如果current 大于或小于number,此方法均有效。如果您只想在current 更大或至少等于number 时停止,则应删除Math.abs

我也建议使用这个版本:

public static boolean stopAtRange(double number, double current, double accuracy) {
  return Math.abs(current - number) <= accuracy;
}

因为它更紧凑,并且针对性能进行了优化。

【讨论】:

    【解决方案2】:

    您的问题有点令人困惑,但我会尽力提供帮助。 :)

    此代码无法编译:

    if(current / number) + accuracy)
    

    首先,您打开了一个括号,然后关闭了两个。你会想要:

    if((current / number) + accuracy)
    

    其次,这不会评估为布尔值(真或假),这是您的 if 语句工作所必需的。你想要:

    public boolean stopAtRange(double number, double current, double accuracy)
    {
        if(Math.abs(current - number) <= accuracy) return true;
        return false;
    }
    

    这会计算出您的数字(100 和 105)之间的差异,并确认它们是否在范围内(10)。

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      如果currentnumber 相差+/-accuracy,则跟随将停止:

      public boolean stopAtRange(double number, double current, double accuracy)
      {
          if( Math.abs(current - number) <= accuracy)
          {
              return true;
          }
          return false;
      }
      

      【讨论】:

        【解决方案4】:

        if 接受一个布尔值,而不是一个双精度值。比如:

        public boolean stopAtRange(double number, double current, double accuracy)
        {
            if(Math.abs(current-number) <= accuracy)
            {
                return true;
            }
            return false;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-05-12
          • 1970-01-01
          • 2015-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多