scanf("%f", &x);
should be
scanf("%lf", &x);
There is a false symmetry for floating points conversion specifiers between printf and scanf.
Also note that lf conversion specifier is equivalent to f conversion specifier in printf (since c99, it was undefined before).
I know that this is fixed when you use %lf when scanning, but why does this happen when using %f?
f conversion specifier in scanf requires an argument of type pointer to float. By passing an argument of type pointer to double you invoke undefined behavior.