Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in double values with scanf in c

I try to read-in 2 values using scanf() in C, but the values the system writes into memory are not equal to my entered values. Here is the code:

double a,b; printf("--------\n"); //seperate lines scanf("%ld",&a); printf("--------\n");  scanf("%ld",&b); printf("%d %d",a,b); 

If I enter 1 and 2, CMD returns a correct, but b = -858993460 Here is what I already tried: using float or int instead of double, using scanf_s, using scanf("%d or %f for %i or %li or %lf or %e or %g ), using fflush(stdin) to clear keyboard buffer, reading in b first, trying like all possible combinations. I found out that there is a problem with the length of double on 32 bit OS, so that you are forced to use scanf("%lf", &f) to read in a double. No matter what I do, second value is always wrong.

I use MS VS express 2012 for Desktop on Windows 7 32 bit OS.

like image 572
user1880009 Avatar asked Dec 05 '12 18:12

user1880009


People also ask

How do I read doubles in scanf?

To read a double, supply scanf with a format string containing the conversion specification %lf (that's a lower case L, not a one), and include a double variable preceded by an ampersand as the second parameter.

Can scanf read two values?

If you have multiple format specifiers within the string argument of scanf, you can input multiple values.

Is %F for double in C?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

What is the input for double in C?

In double data type, the 1 bit for sign representation, 11 bits for the exponent and the remaining 52 bits used for the mantissa.


1 Answers

Use the %lf format specifier to read a double:

double a; scanf("%lf",&a); 

Wikipedia has a decent reference for available format specifiers.

You'll need to use the %lf format specifier to print out the results as well:

printf("%lf %lf",a,b); 
like image 124
simonc Avatar answered Oct 24 '22 04:10

simonc