I am creating a function to calculate the division of 2 numbers that are inside an array. The problem I have is that the division is done the other way around. ej: if I put 10/2 as parameters, the result that returns is 2/10. So how could I solve this error?
Here I leave the complete code, just check the code of the function "fDividir".
Code javascript:
sysc es un sistema que podrás usar para implementar para la creación de tu calculadora.
// inicio de las funciones
//función sumar
const fSumar = function (valores = "0"){
let arregloNum = valores.split(" ");
let oSuma = 0;
for (let i = 0; i < arregloNum.length; i ){
oSuma = parseInt(arregloNum[i]) oSuma;
}
return oSuma;
}
//función restar
const fRestar = function (valores = "0"){
let arregloNum = valores.split("-");
let oResta = 0;
for (let i = 0; i < arregloNum.length; i ){
oResta = parseInt(arregloNum[i]) - oResta;
}
return oResta;
}
// función multiplicar
const fMultiplicar = function (valores = "0"){
let arregloNum = valores.split("×");
let oMultiplicacion = 1;
for (let i = 0; i < arregloNum.length; i ){
oMultiplicacion = parseInt(arregloNum[i]) * oMultiplicacion;
}
return oMultiplicacion;
}
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = 1;
for (let i = 0; i < arregloNum.length; i ){
oDivision = parseInt(arregloNum[i]) / oDivision;
}
return oDivision;
}
// fin de las funciones
console.log(fDividir("10/2")); // 0.2
CodePudding user response:
Change your division function:
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = 1;
for (let i = arregloNum.length - 1; i > 0; i--){
oDivision = parseInt(arregloNum[i]) * oDivision;
}
return arregloNum[0] / oDivision;
}
Note that you were inverting the divisors order...