0

I use CodeBlocks with mingw compiler. If I write

...
    double number;
    printf("Number ? ");
    scanf("%g", &number);
    printf("Number is %g\n", number);
...

and I insert 6.5 in number, output is wrong:

Number ? 6.5
Number is 1.75132e-313

But, if I write

...
    double number;
    number = 6.5;
    printf("Number is %g\n", number);
...

output is correct ( 6.5 ). I have always read that %f, %e and %g could be used with floating point numbers.

  • 1
    Suggestion: change the title of this question. Your second example demonstrates that `printf` prints the correct value, in other words, the error is in `scanf`. – Tim Randall May 31 '22 at 19:40
  • 2
    Use `%lg` in `scanf`. You are reading into `double` not `float`. In `printf` the `'l'` can be omitted. – Eugene Sh. May 31 '22 at 19:41
  • 2
    Your compiler should warn you about this. If it's not, turn up the options till it does. `-Wall -Wextra` is good for gcc. – Shawn May 31 '22 at 19:47

1 Answers1

1

The problem is that the format specifiers %f %e and %g should be used with float values. You've used a double, which uses a different number of bits and has a different memory layout. Passing the address of a double where scanf is expecting the address of a float causes undefined behavior.

Making number a float ought to work fine. Alternatively, pass %lg as the format specifier, if double precision is needed.

Tim Randall
  • 3,795
  • 1
  • 15
  • 37