Reputation: 51
I've made extremely easy program:
#include <stdio.h>
int main()
{
double x;
printf("Write your number \n");
scanf ("%f", &x);
printf("You've written %f \n", x);
return 0;
}
And as a result strange number appears (no matter what x I give):
"You've written 83096261053132580000000000000000000000000000000000000000000
"
What's wrong with this? This program works fine when I change all numbers into an 'int' type.
Upvotes: 0
Views: 2285
Reputation: 153348
Wrong specifier for scanf()
.
With scanf()
, "%f"
matches a float *
, yet coded passed a double *
. Use "%lf"
instead. Code's printf()
is fine. See Correct format specifier for double in printf
double x;
printf("Write your number \n");
// scanf ("%f", &x);
scanf ("%lf", &x);
printf("You've written %f \n", x);
A good compiler should have warned of your incorrect code as suggested by @abligh. Either enable all warnings or consider a new compiler.
When scanning, the &x
must match the proper scanf()
print specifier.
"%f"
matches a float *
"%lf"
matches a double *
The using printf()
things are easier. If a float
or double
is passed, being a variadic function, float
is promoted to double
.
"%f"
and "%lf"
match a double
Upvotes: 1
Reputation: 25129
See what happens when you compile it with warnings enabled:
amb@nimrod-ubuntu:~/so$ gcc -Wall x.c -o x
x.c: In function ‘main’:
x.c:6:9: warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat]
Change %f
to %lf
and the scanf
and printf
functions will correctly take a double
.
Upvotes: 1
Reputation: 13808
You need to use %lf
for scanf and printf.
In other words, this:
#include <stdio.h>
int main()
{
double x;
printf("Write your number \n");
scanf ("%lf", &x);
printf("You've written %lf \n", x);
return 0;
}
Upvotes: 0
Reputation: 786
%f
is used for float
type. You should use %lf
for double
(Long Float).
Upvotes: 0