I have a problem subtracting the values of an array from each other. The addition works perfectly, but the subtraction does not. It always gives me negative numbers, and it 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
I have reviewed the code and since you are starting I think it will be much easier for you in the following way:
If you have any questions about the code, I will gladly answer you.
Clarified what you need by the comments you leave in the description of your question. The error you have is that you basically always make the first number negative because of the logic 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 starting to program, I will not simplify or complicate the code (to optimize your work), but I will place the one that is more didactic and solves your problem simultaneously. Here is the correction to your code:
I hope to be helpful. All the best!
Your code can be simplified/ reduced quite a bit, by using
Array.reduce
.In the case of addition, this method will take care of adding all the elements of the array. In the case of subtraction, we will use a ternary, telling it that, when it is the first element, do not do any operation. This will leave the first value untouched and will subtract all that follow... It's that simple.
I have added another element to the code: control of the prompts, 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 helps you.
You can use the Reduce function