我正在練習我的數學/算法技巧,並試圖只用減法來劃分兩個數字。我非常接近,但我似乎無法處理小數,我不知道爲什麼?在堆棧的最底層,當我調用divide(9,2)時,我注意到我返回「0」,實際上我想返回1/2 - 但不使用除法運算符... inside如果x小於y檢查,我應該在子程序中添加該邏輯嗎?我堅持如何遞歸地將小數點後面的數字添加到三個位置。只用減法遞歸劃分---不能處理小數
var divide = function(x, y) {
//the number of times you need to subtract y from x.
if (y === 0) {
return 0
}
// if
if (x - y === 0) {
return 1;
}
if (x < y) {
// if this is the case, get the value of y - x. ->1
var diff = y - x;
console.log(diff);
// add a zero to the end --> so in our case, 10
diff = String(diff) + '0';
console.log(diff);
diff = Number(diff);
console.log(diff);
// is that now divisible by y? is so how many times? in our case, 5 times.
var decimal = Number(divide(diff, y));
var number = "." + decimal;
//so add .5 to it.
return number;
} else {
return (1 + divide(x - y, y));
}
};
var modulo = function(x, y) {
var val = x;
while (val >= y) {
val -= y;
}
return val;
};
你可能也想跟蹤餘以某種方式。 – ryanyuyu
是的,我正在更新,以包括它的其餘部分 – devdropper87