Home > OS >  Why does this method not give the right multiples of 0.25 in javascript
Why does this method not give the right multiples of 0.25 in javascript

Time:10-22

I am trying to get the multiples of 0.25 but i am getting the wrong output. What am i doing wrong?

let arr1 = []
for (let i = 0.25; i <= 4.25; i  ) {
  //console.log(change)
  if (i > 3) {
    continue;
  }
  i % 0.25 == 0 ? arr1.push(i) : 'cancl'
  console.log(arr1) // i get [0.25, 1.25, 2.25] instead of [0.25, 0.5, 0.75, ...]
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How can i get the write answer/multiples?

CodePudding user response:

Your code doesn't work because i increments i by 1. Increment i by 0.25 instead:

const arr1 = []
for (let i = .250; i <= 4.25; i  = 0.25) {
  arr1.push(i)
}

console.log(arr1)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Because using i , you will get i 1 after iterating

  • Related