Code misbehaves with me!Simple loop problem! | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Code misbehaves with me!Simple loop problem!

Why don't this work properly after I=2?Why does it show 2.0 instead of 2.This is simple loop problem.How do I fix it? https://code.sololearn.com/cJ6O6lCIPQA8

5th Jun 2022, 3:51 PM
KAZI FAISAL MAHMUD
KAZI FAISAL MAHMUD - avatar
2 Respostas
+ 2
0.2 cannot be stored accurately. Every time you add it you accumulate more and more error so 'i' will not be exactly equal to whatever number you're comparing to anymore. This is why compilers show a warning when you try to use the '=='/'!=' operator with floating points. 0.25 (as an example) on the other hand can be stored accurately and it does not have this problem. You could look up comparing floating points with the use of epsilon, but this also doesn't work with big floating point values. Floating points are hard :)
5th Jun 2022, 4:21 PM
Dennis
Dennis - avatar
+ 1
Because of float values... See I actual values in loop every time, observe when I=0,1,2 printf("%.20f\n",i);
5th Jun 2022, 4:24 PM
Jayakrishna šŸ‡®šŸ‡³