我正在练习我的数学/算法技能,并尝试仅使用减法来除两个数字。我非常接近,但我似乎无法处理小数,我不知道为什么?在堆栈的最低级别,当我调用divide(9,2)时,我注意到我返回“0”,而实际上我想返回1/2 - 但不使用除法运算符...如果 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;
};
最佳答案
你会认为这是作弊吗?没有除法或乘法,加法已转换为减法,它返回一个 float ,并且使用递归。但是,需要进行大量的字符串转换,以连接数字并添加符号和小数点。
function divide(x, y, prec) {
if (y == 0) return NaN;
var quot = 0, sign = 1;
if (x < 0) {
sign = 0 - sign;
x = 0 - x;
}
if (y < 0) {
sign = 0 - sign;
y = 0 - y;
}
while (x >= y) {
x -= y;
quot = 0 - (0 - 1 - quot);
}
quot = (sign < 0 ? "-" : "").concat(quot, prec == undefined && x > 0 ? "." : "");
if (x > 0) {
prec = prec || 13;
if (--prec) {
for (var i = 9, temp = x; i; i--) x = 0 - (0 - x - temp);
quot = quot.concat(divide(x, y, prec));
}
}
return parseFloat(quot);
}
alert(divide( 9, 2));
alert(divide( 2, 9));
alert(divide( 9, -2));
alert(divide(-2, 9));
alert(divide(-9, -2));
alert(divide( 0, 9));
alert(divide( 9, 0));
关于javascript - 仅用减法进行递归除法——无法处理小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32897271/