Scanf does not work. need to read twice from the console

I'm not sure what I'm doing wrong, but I can’t read the take from the console. For some reason, reading is wonderful. I am using Xcode.

double n1; // get input from the user printf("Enter first number: "); scanf("%f", &n1); printf("%f", n1); 

This will always print 0 no matter what I enter.

+6
source share
3 answers

%f looking for a float, not a double. If you want to use double, use the %lf format.

As a little interesting, clang warns about this without any additional flags, gcc 4.6 will not warn about it even with -Wall -Wextra -pedantic .

+6
source

%f is for single precision floating-point value (float). The required format specifier is %lf , which means long precision floating-point value (double).

+4
source

All about how data is stored in memory.
Let me first say how long and swim are kept in mind.

  • A double (long float, 64 bits) is stored in memory, for example, or this (small final notation).
  • Where as a float (32 bits) is stored as this (small final notation).
    Also look at this "en.wikipedia.org/wiki/Floating_point#Internal_representation" (all floating data types)

So here you are asking for input as %f (i.e. a float that is 4 bytes and double is 8 bytes), so the compiler takes input from the console and converts it to a float type and stores it in a memory cell (which is on actually 8 bytes) of the variable (here n1 ).

+2
source

Source: https://habr.com/ru/post/911601/


All Articles