Asperger Asperger - 2 months ago 8
Javascript Question

Reducing a number on each iteration until it reaches exactly 0

I want to reduce n to 0 on the last iteration but my calculations are wrong. Im overlooking something. Right now im doing Math.round(n / loops). I need to find a way to disperse the substraction in such a way so that in the last iteration n becomes 0 while the range between each n´s is constant.

function check(a, b) {
let loops = a / b;
let n = 200;

for (let i = 0; i <= loops; i++) {
console.log(n);
n -= Math.round(200 / loops);
}
}

check(60, 10)


Edit: Im sorry but these downvotes are ridiculous.

Answer

The main problem with your code is that the expression n / loop is different in each iteration. You might have intended that this expression was constant, in which case the logic would have been more reasonable.

Use a separate variable that starts with the value of n and then is the subject of the subtractions, but without changing the original value of n that is used in the expression n / loop:

function check(a, b) {
    let loops = a / b;
    let n = 200; // don't change n after this.
    let n2 = n; // use a separate variable for that.
    for (let i = 0; i <= loops; i++) {
        console.log(Math.round(n2)); // only round in output
        n2 -= n / loops; // use n, but only change n2
    }
}

check(60,10);

Comments