-1

You need to always be true in the console)

Without gaps, without rounding to the integer, without changing the comparison operator and the general calculation logic, as well as the loop condition )

P.S. This is an interview task for junior level ...

for (let i = 0; i <= 10; i++) {
  console.log(i + ':' + ((i * 0.1) == (i / 10)));
}
// needed to always true in console.log
vipdanek
  • 1
  • 1
  • What CAN be changed then? Also: [Is floating point math broken?](https://stackoverflow.com/questions/588004) – adiga Jan 21 '21 at 13:34
  • 4
    What are you trying to achieve ? – Weedoze Jan 21 '21 at 13:35
  • 1
    i think he wants to test our coding skills :)\ – Amaarockz Jan 21 '21 at 13:37
  • @Weedoze they probably want to get the same value when a number multiplied by 0.1 and divided by 10. But, not sure what can be changed in the code. Because of [how floating points work](https://stackoverflow.com/questions/588004), it is not possible with the current code – adiga Jan 21 '21 at 13:37
  • If you have any question about the given code, please add it to your question by editing it – Nico Haase Feb 01 '21 at 07:42

1 Answers1

1

I would just create a function to compare the difference to a threshold e.g. 0.001.

/**
 * Determines if two floating value are equal within a threshold
 * @param {Number} a - First floating value
 * @param {Number} b - Second floating value
 * @param {Number} [t=0.001] - Threshold of difference
 * @return {boolean} Whether the difference is less than the threshold
 */
const equalsFloat = (a, b, t = 0.001) => Math.abs(a - b) < t;

for (let i = 0; i <= 10; i++) {
  console.log(`${i}: ${equalsFloat(i * 0.1, i / 10)}`);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132