First off,
printf ("%lf", &x);
will try to print the address of x
rather than its value, and this is clearly into undefined behaviour territory(a). A half-decent compiler should warn you about this such as, with gcc
:
program.c: In function 'main':
program.c:13: warning: format '%lf' expects argument of type
'double', but argument 2 has type 'double *' [-Wformat=]
printf ("%lf\n", &x);
^
Secondly, the normal printf
specifier for double is %f
rather than %lf
. You can use the latter since the standard states it has no effect on certain data types but it's a bit of a waste doing so.
So what you need is actually:
printf ("%f", x);
The general rule is that you pass addresses to scanf
because it needs to populate the objects at those addresses. For printf
, you just pass the object itself (yes, even if the data is a pointer that you want printed as a pointer rather than pointing the object being pointed to).
And, finally, to make your code more robust, you would be wise to detect a problem with scanf
since, it there's a problem with the input that leaves x
set to zero, the program will continuously try to read that input, resulting in an infinite loop.
So a good starting point, taking all those comments into consideration, would be:
#include <stdio.h>
#include <math.h>
int main (void) {
double x = 0;
while (x <= 0) {
printf ("Enter a digit greater than 0.\n");
if (scanf ("%lf", &x) != 1) {
printf ("Invalid input\n");
return 1;
}
}
printf ("%f\n", x);
return 0;
}
(a) Specifically, from ISO C11 7.21.6.1 /9
:
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.