將真分數轉換為帶分數 - JavaScript
真分數
存在於 p/q 形式的稱為真分數(p 和 q 均為自然數)
帶分數
假設我們用分數的分母(假設是 b)來除分子的值(假設是 a),得到商 q 餘數 r。
分數 (a/b) 的帶分數形式為 -
qrb
可讀作“q 個和 r 個 b 分之幾”。
我們需要編寫一個 JavaScript 函式,輸入一個由兩個數字組成、代表真分數的陣列,則函式應該返回一個由三個數字組成的陣列、代表其帶分數形式
示例
以下是程式碼 -
const arr = [43, 13]; const properToMixed = arr => { const quotient = Math.floor(arr[0] / arr[1]); const remainder = arr[0] % arr[1]; if(remainder === 0){ return [quotient]; }else{ return [quotient, remainder, arr[1]]; }; }; console.log(properToMixed(arr));
輸出
以下是控制檯的輸出 -
[ 3, 4, 13 ]
廣告