Weird behaviour of for loops (numerical precision of double)

Hello,

can you explain me why

[code]#include <stdio.h>

int main(void) {
for (double mass = 100; mass < 200; mass += 0.1)
printf("%lf\n", mass);
return 0;
}
[/code]

actually prints 130?

[quote=“rene”]Hello,

can you explain me why

[code]#include <stdio.h>

int main(void) {
for (double mass = 100; mass < 200; mass += 0.1)
printf("%lf\n", mass);
return 0;
}
[/code]

actually prints 130?[/quote]

What do you mean by "actually prints 130?"
How do you compile/execute it?

BTW. The “%lf\n” format string is wrong. You should simply have “%f\n”. According to “man 3 printf”, the “l” is valid for “integer/character/string conversion” only (and the “f” stands for a “double argument”).

[quote=“tpochep”][quote=“rene”]Hello,

can you explain me why

[code]#include <stdio.h>

int main(void) {
for (double mass = 100; mass < 200; mass += 0.1)
printf("%lf\n", mass);
return 0;
}
[/code]

actually prints 130?[/quote]

What do you mean by "actually prints 130?"
How do you compile/execute it?[/quote]

sorry for the typo, I meant 200
it seems to be just a approximation/double representation issue… but I wouldn’t have expected it with such numbers

I am compiling naively with

gcc main.C ./a.out

Try 199.99999999999 instead of 200, then add one 9 in the end and try again.