0

When I use float, like this:

#include <stdio.h>

int main()
{
    float g;
    float f;

    scanf("%f", &f);
    g = f / .5;
    printf("%f", g);
    return 0;
}

and enter 2 I get back 4.000. When instead in the place of float I use double the result is always 0.000. Why is this am I missing something?

bill chill
  • 15
  • 4
  • _When instead in the place of float I use double the result is always 0.000._ ... because you need `scanf("%lf", &f);` for a `double` – David Ranieri Dec 20 '21 at 20:25
  • 1
    If you possibly can, use a better compiler, or enable more warnings. A modern compiler would have told you precisely what you did wrong here. – Steve Summit Dec 20 '21 at 20:26
  • @SteveSummit What c compilers would you suggest? I'm just starting out. – bill chill Dec 20 '21 at 20:48

2 Answers2

2
#include <stdio.h>

int main()
{
    double g;
    double f;

    scanf("%lf", &f);
    g = f / .5;
    printf("%lf", g);
    return 0;
}

You need to use the format specifier specifically for doubles (%lf) here.

See format string specifications for more information about different format specifiers.

codyne
  • 552
  • 1
  • 9
1

As, Scanf not reading in double,

You lied to the compiler: when scanning, %f says you supply a pointer to float. But you provided a pointer to double.

To fix, either use %lf or declare input as float.

Note that there is an asymmetry with printf formats, which uses %f for both float and double arguments. This works because printf arguments are promoted to double (and are not pointers).

script0
  • 387
  • 2
  • 12