這是一個簡單的數學問題,題目爲: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)
}
}
複製代碼