简体   繁体   中英

Issue in Format Specifiers of C

How is %+8.9d different from %8.9d in C?

Let's take an example

int a=444;

float b=444;

printf("%8.9d",a);
printf("%8.9f",b);
printf("%+8.9d",a);
printf("%+8.9f",b);

Output:

000000444
444.000000000
+000000444
+444.000000000

Why are 6 zeros present before the number? (that too only in integer numbers)

What is significance of + here?

How is + getting printed in the output?

Why are 6 zeros present before the number?

You requested for a minimum of 9 digits to appear (when printing the int ).

Quote https://en.cppreference.com/w/c/io/fprintf ,

(optional) . followed by integer number or * , or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int , which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is taken as zero. See the table below for exact effects of precision .

From the referenced table, for d :

Precision specifies the minimum number of digits to appear. The default precision is 1 . If both the converted value and the precision are 0 the conversion results in no characters.


How is + getting printed in the output?

You requested for a the sign of the number to appear.

Quote https://en.cppreference.com/w/c/io/fprintf ,

+ : the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM