时针和分针相差多少度

问题描述

这是一个简单的数学问题,题目为:30分钟时时针和分针相差多少度?
题目分析:
  1. 没说明究竟是何时,只定了分钟为30分钟。
  2. 时钟只有十二个小时,所以一个小时就是30度,一分钟就是6度。
  3. 假设如今为h时m分,那么分针的度数为:6 * m;时针的度数为:30 * h + m / 2(以零点为参考点);那么时针的度数减去分针的度数的绝对值就是它们之间相差的度数(|30 * h - 11 / 2 m|),有一点须要注意,那就是时针与分针之间相差的最大度数为180度,因此应该作一次判断。bash

解决问题

/**
 * 计算分针和时针之间相差的度数
 * @param {Number} h 
 * @param {Number} m 
 */
function hoursAndMinute (h, m = 15) {
  if (isNullUnderfined(h) || isNullUnderfined(m) || h > 24 || m > 60) { throw new Error('args is not permission!'); }
  const H = h % 12;
  const hEdage = 30 * H + m / 2;
  const mEdage = 6 * m;
  const edage = Math.abs(hEdage - mEdage);
  return edage > 180 ? 360 - edage : edage;
};

function isNullUnderfined (val) {
  const result = /(?:Null)/.test(Object.prototype.toString.call(val)) || typeof val === 'undefined';
  return result;
}
复制代码

能够跑一下测试一下可靠行:dom

function test (num = 30000) {
  for (let i = 0; i < num; i++) {
    const hour = Math.floor(Math.random() * 24);
    const minute = Math.floor(Math.random() * 60);
    const result = hoursAndMinute(hour, minute);
    console.log('idnex ' + i + ': ' + hour + '时' + minute + ' result: ' + result);
  }
}

test();
复制代码

上几个特殊状况:
函数


测试辅助函数:

/**
 * 验证结果可靠性
 */
function validate () {
  for (let h = 0; h < 24; h++) {
    for (let m = 0; m < 60; m++) {
      const val = Math.abs((30 * h) - (11 / 2 * m))
      if (val === 180 || val === 0) {
        console.log(h + ' H ' + m + 'M')
        console.log('validate: ' + hoursAndMinute(h, m))
      } else if (hoursAndMinute(h, m) > 180 || hoursAndMinute(h, m) < 0) {
        console.log('have a result is not right: ' + h + ' H' + m + ' M')
      }
    }
  }
}
/**
 * 查看运算结果
 * @param {Number} num 运算次数
 */
function test (num = 30000) {
  for (let i = 0; i < num; i++) {
    const hour = Math.floor(Math.random() * 24)
    const minute = Math.floor(Math.random() * 60)
    const result = hoursAndMinute(hour, minute)
    console.log('idnex ' + i + ': ' + hour + '时' + minute + ' result: ' + result)
  }
}
复制代码
相关文章
相关标签/搜索