2
double d;
scanf("%f", &d);
printf("%f", d);

result:

input: 10.3

output: 0.00000

Why? i think output should be 10.3 visual studio 2008.

Community
  • 1
  • 1
Sergey
  • 21
  • 1
  • 1
  • 2
  • now that your problem is solved, http://stackoverflow.com/questions/2377733/how-does-this-program-work might clarify things a bit more! – Lazer Mar 07 '10 at 19:12

2 Answers2

9

For scanf(), %f is for a float. For double, you need %lf. So,

#include <stdio.h>
main() {
    double d; 
    scanf("%lf", &d); 
    printf("%f\n", d);
}

with input 10.3 produces 10.300000.

caf
  • 233,326
  • 40
  • 323
  • 462
Ramashalanka
  • 8,564
  • 1
  • 35
  • 46
  • +1 for %4.1lf format string Sergey could view this: http://www.cplusplus.com/reference/clibrary/cstdio/printf/ – stacker Mar 07 '10 at 10:13
  • 6
    `%lf` is needed for `scanf()`, but for `printf()`, `%f` means `double` (and works with `float` too, because `float` is promoted to `double` in the variable portion of the argument list). `%lf` is meaningless to `printf()`. – caf Mar 07 '10 at 10:20
  • printf is a vararg function, so argument promotion need not apply - compiler does not know argument types beyond format string. Said that, %lf is needed. – el.pescado - нет войне Mar 07 '10 at 14:18
  • el.pescado: There are a particular set of argument promotions that are always applied to arguments in the variable portion of the argument list (they are the same as those applied to the arguments of a function declared without a prototype). – caf Mar 08 '10 at 06:33
1

Try replacing %f with %lf. %f is used when dealing with float, not double. (or alternately, you could make d a float).

MAK
  • 26,140
  • 11
  • 55
  • 86