How to perform mathematical operations with the values of an array

1

I have a problem subtracting the values of an array from one another. The sum works perfectly, but the subtraction does not work. It always makes me negative numbers, and that would not be the case.

This is my code:

var numbers = [];

var userTimes = prompt('Cuantas operaciones quieres hacer?')

for (var i=0; i<userTimes; i++) {
    var user = parseInt(prompt('Escribe un valor'));
    numbers.push(user);
    console.log(numbers);
}

function sum() {
    var acc = 0;
    numbers.forEach(function(obj){
        acc += obj;
    })
    return acc;
}
console.log('La suma entre ' + numbers + ' hace: ' + sum());

function subs() {
    var acc = 0;
    numbers.forEach(function(obj){
        acc -= obj;
    })
    return acc;
}
console.log('La resta entre ' + numbers + ' hace: ' + subs());

//Output sum: La suma entre 8,5,1 hace: 14
//Output subs: La resta entre 8,5,1 hace: -14
    
asked by jaumeserr 17.06.2018 в 13:01
source

4 answers

2

I have reviewed the code and since you are starting, I think it will be much easier for you in the following way:

var numbers = [];

function askNumsToCalculate() {

    var userTimes = prompt('Cuantas operaciones quieres hacer?')

    for (var i=0; i<userTimes; i++) {
        var user = parseInt(prompt('Escribe un valor'));
        numbers.push(user);
    }

    if(numbers.length === 1) {
        console.log('La raíz cuadrada de ' + numbers[0] + ' es: ' + Math.sqrt(numbers[0]).toFixed(3));

    } else if(numbers.length === 2) {
        operationsNums();
    }
}

askNumsToCalculate();


function operationsNums() {

    function resta() {

        var result = [];

        if(result.length === 0) {
            result.push(numbers[0]);    
        }

        for (var j=1; j<numbers.length; j++) {
            var resta = result[0] - numbers[j];
            result = []
            result.push(resta)
        }
        console.log(result);
    }

    resta();
operationsNums();

If you have any questions about the code, I will happily reply.

    
answered by 18.06.2018 / 10:32
source
1

Your code can be simplified / reduced enough, by using Array.reduce .

In the case of the sum, this method will be responsible for adding all the elements of the array. In the case of subtraction, we will use a ternary, telling you that, when the first element is done, do not do any operation. This will leave the first value intact and subtract all that come next ... It's that simple.

I have added another element to the code: control of the prompt, so that the user does not enter negative numbers in the first case, and so that he only enters numbers in the second case.

I hope it serves you.

do {
  var userTimes = parseInt(prompt("¿Cuántas operaciones quieres hacer?", ""), 10);
} while (isNaN(userTimes) || userTimes < 1);

var numbers = [];

for (var i = 0; i < userTimes; i++) {
  do {
    var user = parseInt(prompt("Escribe un valor", ""), 10);
  } while (isNaN(user));

  numbers.push(user);
}



console.log("La suma  es: " + add(numbers));
console.log("La resta es: " + sub(numbers));

/*Función para sumar*/
function add(arrNumbers) {
  var resultado = arrNumbers.reduce(function(a, b) {
    return a + b;
  });
  return resultado;
}

/*Función para restar*/
function sub(arrNumbers) {
  var resultado = arrNumbers.reduce(function(a, b, i) {
    /*Restará sólo después del 1er elemento*/
    return (i >= 1) ? a - b : 0;
  });
  return resultado;
}
    
answered by 17.06.2018 в 23:44
1

Clarified what you need for the comments you leave in the description of your question. The error you have is that basically you always transform the first number in negative by the logic that you used in your code. To achieve a correct algebraic sum you must add a condition that allows you to capture the first number and add it instead of subtracting it in order to perform the operation correctly.

As you are beginning to program, I will not simplify or complicate (to optimize your work) the code, but I will place the one that is more didactic and solves your problem simultaneously. Then the correction to your code:

var numbers = [];
var cont=1;

var userTimes = prompt('Cuantas operaciones quieres hacer?')

for (var i=0; i<userTimes; i++) {
    var user = parseInt(prompt('Escribe un valor'));
    numbers.push(user);
    console.log(numbers);
}

function sum() {
    var acc = 0;
    numbers.forEach(function(obj){
        acc += obj;
    })
    return acc;
}
console.log('La suma entre ' + numbers + ' hace: ' + sum());

function subs() {
    var acc = 0;
    numbers.forEach(function(obj){
    	if(cont==1){
        acc += obj;
        cont++;
      }
      else{
      	acc -= obj;
      }
    })
    return acc;
}
console.log('La resta entre ' + numbers + ' hace: ' + subs());

//Output sum: La suma entre 8,5,1 hace: 14
//Output subs: La resta entre 8,5,1 hace: -6

I hope it helps. Greetings!

    
answered by 17.06.2018 в 14:27
0

You can use the Reduce

function

var numbers = [];
var cont=1;
var userTimes = prompt('Cuantas operaciones quieres hacer?')

for (var i=0; i<userTimes; i++) {
    var user = parseInt(prompt('Escribe un valor'));
    numbers.push(user);
}
function sumar(a , b){
  return a + b;
}
function restar(a , b){
  return a - b; 
}
function dividir(a , b){
  return a / b; 
}
function multiplicar(a , b){
  return a * b; 
}
var acciones = [sumar, restar, dividir, multiplicar];

for (let i = 0 ; i <= acciones.length -1 ; i++){
console.log(acciones[i].name +' '  + numbers.toString() + ' =' + numbers.reduce(acciones[i]));
}
    
answered by 18.06.2018 в 16:05