Is there a difference in using% f,% e,% g,% E or% G with scanf?

In C, is there a difference in the format specifiers% f,% e,% g,% E and% G when used in reading in a float variable with scanf? That is, will there be code snippet behavior

float x; scanf("%<one of f, e, g, E, G>", &x); 

always depends on the choice of qualifier?

At first, I suggested that% f would interpret the decimal notation correctly, and% e would interpret the scientific notation correctly, but on my system, each one works fine anyway. But maybe my system is just liberal ...

I could not find a definite statement about this in my books or on the Internet ...

+8
c floating-point scanf
source share
4 answers

The above answer applies to C ++, but the same is true for C.

From "7.19.6.2 fscanf function" to "The final version of the C99 standard with corrections TC1, TC2 and TC3 is included, formatted as a draft" (link copied from http://en.wikipedia.org/wiki/C99 ):

a, e, e, f
Matches an optionally signed floating-point, infinity, or NaN number, the format of which is the same as expected for a sequence of strtod entities. The corresponding argument should be a pointer to floating.

The conversion qualifiers A, E, F, G, and X are also valid and behave the same as a, e, f, g, and x , respectively.

So %f, %e, %g, %E, %G all behave the same when scanning numbers, as you experienced it.

+8
source share

f,e,g all for a floating point number

From doc : -

A series of decimal digits, optionally containing a decimal point, optionally preceding the sign (+ or -), and optionally followed by e or E and a decimal integer (or some other sequence supported by strtod). C99 compliant implementations also support floating point hexadecimal if preceded by 0x or 0X.

Also check out this reference , which says it ( f,e,g ) matches a floating point number.

+2
source share

C displays both floating and double variables up to six decimal places. This does NOT apply to the precision on which the number is actually stored, only the number of decimal places of printf() to display these types of variables.

The following program illustrates how different types of data are declared and displayed:

 #include <stdio.h> main() { float a = 23.567; double b = 11e+23; printf("Float variable is %f\n", a); printf("Double variable is %e\n", b); } 

OUTPUT

 Float variable is 23.567000 Double variable is 11.000000e23 
0
source share
 %i=defaults for decimals %u=gives the memory address of the variable %p=gives the value of pointer %e=gives the scientific notation %g=handles large floating numbers 
-2
source share

All Articles